I have a dataframe like following:
df<- data.frame(ID=c(1,1,1,2,2,3,3,3,4,4),weight=c(0,0,11,0,10,12,0,0,13,0))
I want to repeat the value of column weight based on column ID.
my expected output would be like this:
ID weight
1 1 11
2 1 11
3 1 11
4 2 10
5 2 10
6 3 12
7 3 12
8 3 12
9 4 13
10 4 13
by the code below I have got some error:
df1<- df %>% group_by(ID) %>% rep(weight)
>Solution :
You may try
library(dplyr)
df %>%
group_by(ID) %>%
mutate(weight = sum(unique(weight)))
ID weight
<dbl> <dbl>
1 1 11
2 1 11
3 1 11
4 2 10
5 2 10
6 3 12
7 3 12
8 3 12
9 4 13
10 4 13