Replace missing value with previous value

r zoo
user2033963 picture user2033963 · Feb 1, 2013 · Viewed 9.1k times · Source
Event,Time,Bid,Offer
Quote,0.458338,9.77,9.78
Order,0.458338,NA,NA
Order,0.458338,NA,NA
Order,0.458338,NA,NA
Quote,0.458363,9.78,9.79
Order,0.458364,NA,NA

I have a Data frame like this I want to write a efficient code to fill up the NA with previous Quote bid and ask, Time is sorted, and only Quote contains bid and ask field (preferably vectorization)

so it becomes

Event,Time,Bid,Offer
Quote,0.458338,9.77,9.78
Order,0.458338,9.77,9.78
Order,0.458338,9.77,9.78
Order,0.458338,9.77,9.78
Quote,0.458363,9.78,9.79
Order,0.458364,9.78,9.79

thanks

Answer

Gavin Simpson picture Gavin Simpson · Feb 1, 2013

The na.locf() function in the zoo package is your friend here. The locf stands for "last one carried forward". With your data:

dat <- read.table(text = "Event,Time,Bid,Offer
Quote,0.458338,9.77,9.78
Order,0.458338,NA,NA
Order,0.458338,NA,NA
Order,0.458338,NA,NA
Quote,0.458363,9.78,9.79
Order,0.458364,NA,NA
", header = TRUE, sep = ",")

require(zoo)

dat2 <- transform(dat, Bid = na.locf(Bid), Offer = na.locf(Offer))

Produces.

> dat2
  Event     Time  Bid Offer
1 Quote 0.458338 9.77  9.78
2 Order 0.458338 9.77  9.78
3 Order 0.458338 9.77  9.78
4 Order 0.458338 9.77  9.78
5 Quote 0.458363 9.78  9.79
6 Order 0.458364 9.78  9.79