df_input is the data frame I have and I want to transform it into df_output.
For instance, as the year 2001-2003 is assembly=1 and we have a winner in 2001. It means we have a winner as long as the assembly doesn't change.
df_input <- data.frame(winner = c(1,0,0,0,2,0,0,0,1,0,0,0,0),
party = c("A",0,0,0,"B",0,0,0,"C",0,0,0,0),
assembly= c(1,1,1,2,2,2,3,3,3,3,4,4,4),
year = c(2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013))
df_output <- data.frame(winner = c(1,1,1,0,2,2,0,0,1,1,0,0,0),
party = c("A","A","A",0,"B","B",0,0,"C","C",0,0,0),
assembly= c(1,1,1,2,2,2,3,3,3,3,4,4,4),
year = c(2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013))
How can I update the same information as in the winner column depending on "assembly"?
EDIT: How to do it if there is an additional string variable, "party"? Look at the edit:
I get the following error after implementing this code:
df_output <- df_input %>%
mutate(df_input$party = if_else(is.na(df_input$party)==FALSE, df_input$party, NA_real_)) %>%
group_by(assembly) %>%
fill(df_input$party) %>%
ungroup() %>%
replace_na(list(df_input$party = 0))
Error:
Error: unexpected '=' in:
" ungroup() %>%
replace_na(list(df_input$party ="