Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

repeat existed row for a column based on another column

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading