R 根据组内的引用按组更改值
给定一个包含已定义组的表,每个组中 我只有一个引用(查询),我想更改列的所有值 基于参考值。R 根据组内的引用按组更改值,r,dataframe,dplyr,tidyverse,mutate,R,Dataframe,Dplyr,Tidyverse,Mutate,给定一个包含已定义组的表,每个组中 我只有一个引用(查询),我想更改列的所有值 基于参考值。 该值仅为1或-1 想法是: -如果参考值等于1,则保持所有值不变 -但是如果引用是-1,那么所有的值都应该乘以-1,这样引用变成了1,值为1的项目变成了-1 -此外,修改后的组应具有相反的顺序 我试着这样做: library(tidyverse) item <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l") g
该值仅为1或-1 想法是:
-如果参考值等于1,则保持所有值不变
-但是如果引用是-1,那么所有的值都应该乘以-1,这样引用变成了1,值为1的项目变成了-1
-此外,修改后的组应具有相反的顺序 我试着这样做:
library(tidyverse)
item <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l")
grou <- c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
quer <- c(0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0)
dir <- c(1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, -1)
ds <- tibble(item = item,
group = grou,
query = quer,
direction = dir)
ds %>%
group_by(group) %>%
mutate(
direction = ifelse(
direction[query == 1] == 1, direction, (-1 * direction)
)
)
库(tidyverse)
项目以下是一种方法:
ds %>%
rowid_to_column("id") %>%
group_by(group) %>%
mutate(tmp = max(query * direction) - 0.5,
direction = tmp * 2 * direction) %>%
arrange(id * tmp, .by_group = TRUE) %>%
select(-c(id, tmp))
结果是:
# A tibble: 12 x 4
# Groups: group [4]
item group query direction
<chr> <dbl> <dbl> <dbl>
1 a 1 0 1
2 b 1 1 1
3 c 1 0 1
4 d 2 0 -1
5 e 2 1 1
6 f 2 0 1
7 i 3 0 -1
8 h 3 1 1
9 g 3 0 -1
10 l 4 0 1
11 k 4 1 1
12 j 4 0 1
#一个tible:12 x 4
#分组:分组[4]
项目组查询方向
1A 10 1
2b11
3C101
4D20-1
5 e 2 1 1
6F201
7 i 3 0-1
8小时31
9 g 30-1
10升4 0 1
11 k 4 1 1
12 j 4 0 1
你能显示预期的输出吗?@markus我添加了示例,并修复了方向(我上次编辑时忘记了)@SvenHohenstein不,输出看起来不错。仅当query==1
为direction==1
时,才应更改这些值。因此,它严格取决于组中方向查询==1的值,如果不是组中的所有元素都必须保持原样的话。看起来你可能希望在变异时使用case\u,但我不太理解逻辑,无法写出这一点。这个小组应该在这里取得什么成就?@emilykoth它应该归档小组专栏。嗨,斯文!它还需要颠倒项目的顺序,因此我建议:ds%>%groupby(group)%>%mutate(direction2=(max(query*direction)-0.5)*2*direction,item2=ifelse((max(query*direction)-0.5)*2*direction!=direction,rev(item),item))
我这样做了,但我没有反转修改过的组ds%%>%left\u join(ds%%>%filter(query==1)%%>%select(group,direction)%%>%rename(factor=direction),by=“group”)%%>%mutate(direction=direction*factor)%%>%select(-factor)
编辑:ds%%>%left\u join(ds%%>%filter(query==1)%%>%select(group,direction)%%>%rename(factor=direction),by=“group”)%%>%mutate(direction=direction*factor)%%>%group\u by(group,factor)%%>%arrange(如果其他(factor==1,item,rev(item))%%>%ungroup()%%>%arrange(group)%%>%select(-factor)
@AurelianoGuedes查看我的答案的更新。现在受影响组中的行顺序颠倒了。@SvenHohenstein似乎你的解决方案比我的好,因为我的解决方案不能很好地处理所有情况。谢谢。
ds %>%
rowid_to_column("id") %>%
group_by(group) %>%
mutate(tmp = max(query * direction) - 0.5,
direction = tmp * 2 * direction) %>%
arrange(id * tmp, .by_group = TRUE) %>%
select(-c(id, tmp))
# A tibble: 12 x 4
# Groups: group [4]
item group query direction
<chr> <dbl> <dbl> <dbl>
1 a 1 0 1
2 b 1 1 1
3 c 1 0 1
4 d 2 0 -1
5 e 2 1 1
6 f 2 0 1
7 i 3 0 -1
8 h 3 1 1
9 g 3 0 -1
10 l 4 0 1
11 k 4 1 1
12 j 4 0 1