具有组内选择功能的dplyr变异

时间:2018-09-24 10:19:55

标签: r function dplyr mutate

我正在尝试在dplyr中的mutate变量中使用一个选择函数。

df <- data.frame(city = c(rep(1,4),rep(2,4)), 
            year = rep(1,8),
            victory = rep(c(1,0,0,0),2),
            affiliation = c("a","b","c","d","e","f","g","h"))

无效代码:

data %>% 
  group_by(.dots=c("city","year")) %>% 
  mutate(group_affiliation = affiliation(victory==1)) 

期望:

group_affiliation = c(rep("a",4), rep("e",4)

对于每个城市,年份组我试图获取由胜利== 1定义的条目的从属值,然后突变为整个组。

P.S。我本来可以分为两部分,重新​​合并组,但是我的计算机无法处理矢量大小

1 个答案:

答案 0 :(得分:3)

library(dplyr)      
df %>% 
   group_by(city,year) %>% 
   mutate(group_affiliation = affiliation[victory==1])