Applying Rolling Functions by Group

33 views Asked by At

I am trying to create a new variable in my dataset. The new variable is the three year moving average of the house vote margin. I want to group by the year, state, and congressional district to create this new variable.

I have tried to use both rollmean and rollapply. However, the new column in my dataset is blank. The new column is filled with only NA's. Any advice would be greatly appreciated!

test1 <- votemargin %>% group_by(year, state_po, cd) %>% mutate(rollavg3 = rollapply(house_votemargin, 3, mean, fill=NA))

test2 <- votemargin %>% group_by(year, state_po, cd) %>% mutate(rollavg3 = rollmean(house_votemargin, 3, fill=NA, align='right'))

0

There are 0 answers