12

I have a data frame in with data as follows

Col1    Col2 
20      NA    
25      NA     
15      NA
NA      10
NA      15

and so on... I am looking to reshape it as follows

Col1     Col2
20        10
25        10
15        10
15        10
15        15

Basically to forward or backward fill NA values with the first occurring non NA value. I tried a variation of Carry last Factor observation forward and backward in group of rows in R, but was unable to get it to work... Thanks in advance!

Community
  • 1
  • 1
FlyingPickle
  • 1,047
  • 1
  • 9
  • 19
  • 10
    `tidyr::fill` works, e.g. `df %>% fill(everything()) %>% fill(everything(), .direction = 'up')` – alistaire Mar 20 '17 at 23:23
  • @alistaire: Thanks! I believe when you mention everything() its ncol(df) to account for doing this action over all columns in the DF? – FlyingPickle Mar 20 '17 at 23:42
  • `everything()` is a helper function from dplyr that just tells the function to act on all the columns. Specify the columns any way you could in `dplyr::select`. – alistaire Mar 20 '17 at 23:44

1 Answers1

10

We can do this with na.locf from zoo

library(zoo)
na.locf(na.locf(df1), fromLast = TRUE)
#  Col1 Col2
#1   20   10
#2   25   10
#3   15   10
#4   15   10
#5   15   15
akrun
  • 874,273
  • 37
  • 540
  • 662