Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward and backward fill data frame in R [duplicate]

Tags:

r

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!

like image 763
FlyingPickle Avatar asked Mar 20 '17 23:03

FlyingPickle


People also ask

What is forward and backward fill?

Forward filling and backward filling are two approaches to fill missing values. Forward filling means fill missing values with previous data. Backward filling means fill missing values with next data point.

How do you repeat a column in a DataFrame in R?

First of all, create a data frame. Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.

How do I reverse a dataset in R?

Rotating or transposing R objects You can rotate the data. frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.


1 Answers

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
like image 181
akrun Avatar answered Oct 16 '22 13:10

akrun