mutated function in several columns

36 views Asked by At

I have a data frame like this one, with several rows for the same subject

ID  alcohol_1   alcohol_2
1   1           0
1   0           1
2   0           1
2   0           0

When I have "1" for the alcohol_1 and alcohol_2 columns, I would like to be able to repeat them on all the rows of the same subject to have a df like this

 ID alcohol_1   alcohol_2
 1  1           1
 1  1           1
 2  0           1
 2  0           1

I can do it column by column with these functions:

df<-df%>%
  group_by(ID) %>%  mutate(alcohol_1= max(alcohol_1))

df<-df%>%
  group_by(ID) %>%  mutate(alcohol_2 = max(alcohol_2))

But I would like to be able to automate this (with a function, a loop or whatever) as I have many more columns in my real df.

Thanks in advance for the help

0

There are 0 answers