Home > Net >  repeat existed row for a column based on another column
repeat existed row for a column based on another column

Time:07-07

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)

CodePudding user response:

Another possible solution, based on the idea of converting first the zeros to NA and then using tidyr::fill:

library(tidyverse)

df %>%
  mutate(weight = na_if(weight, 0)) %>% 
  group_by(ID) %>% 
  fill(weight, .direction = "updown") %>% 
  ungroup

#> # A tibble: 10 × 2
#>       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

CodePudding user response:

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
  • Related