copy the above row values to cells

Hi my dataset looks like

data <- data.frame(id = c(1,1,2,2,3,3,4,4),
                time= c(0,10,0,5,0,20,0,30),
                freq=c(1,NA,2,NA,2,NA,1,NA))
  1. I want to replace NA's with above row value
data2 <-  data.frame(id = c(1,1,2,2,2,2,3,3,3,4,4),
                time= c(0,10,0,5,10,15,0,10,20,0,30),
                freq=c(1,NA,2,NA,NA,NA,2,NA,NA,1,NA))

How can i replace NA's with the freq values of same ID

Thanks

I think you the fill function from the tidyr package will help you. Take a look at the examples below, is this what you're looking for?

data <- data.frame(id = c(1,1,2,2,3,3,4,4),
                   time= c(0,10,0,5,0,20,0,30),
                   freq=c(1,NA,2,NA,2,NA,1,NA))

data2 <-  data.frame(id = c(1,1,2,2,2,2,3,3,3,4,4),
                     time= c(0,10,0,5,10,15,0,10,20,0,30),
                     freq=c(1,NA,2,NA,NA,NA,2,NA,NA,1,NA))

library(magrittr) # to get pipe operator

data %>%
  tidyr::fill(freq)
#>   id time freq
#> 1  1    0    1
#> 2  1   10    1
#> 3  2    0    2
#> 4  2    5    2
#> 5  3    0    2
#> 6  3   20    2
#> 7  4    0    1
#> 8  4   30    1

data2 %>%
  tidyr::fill(freq)
#>    id time freq
#> 1   1    0    1
#> 2   1   10    1
#> 3   2    0    2
#> 4   2    5    2
#> 5   2   10    2
#> 6   2   15    2
#> 7   3    0    2
#> 8   3   10    2
#> 9   3   20    2
#> 10  4    0    1
#> 11  4   30    1

Created on 2020-09-17 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.