1
votes

I am trying to use a select function within a mutate one in dplyr after grouping.

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"))

Non working Code:

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

Expectation:

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

For each city, year group I am trying to get the affiliation value for the entry defined by victory == 1 and then mutating to the whole group.

P.S. I would have done it in two parts, re-merging the groups but my computer is incapable of handling the vector size

1

1 Answers

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