foc
foc

Reputation: 967

Fill missing values from bottom to up

Example of problem

           date          X         Y
 2012-07-05 00:01:19   0.0122     NA
 2012-07-05 03:19:34   0.0121     NA
 2012-07-05 03:19:56   0.0121   0.027
 2012-07-05 03:20:31   0.0121   0.027
 2012-07-05 04:19:56   0.0121   0.028
 2012-07-05 04:20:31   0.0121   0.028
 2012-07-05 04:20:50   0.0121   0.028

How I can fill the NA with the 0.027 in Y column?

Upvotes: 0

Views: 211

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

Here's a solution in base R. If dat is the name of your data frame, you can try:

within(dat, Y[is.na(Y)] <- na.omit(Y)[1])

Upvotes: 4

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

You can use na.locf from the "zoo" package:

library(zoo)
na.locf(mydf, fromLast=TRUE)
#        X     Y
# 1 0.0122 0.027
# 2 0.0121 0.027
# 3 0.0121 0.027
# 4 0.0121 0.027
# 5 0.0121 0.028
# 6 0.0121 0.028
# 7 0.0121 0.028

Where "mydf" is:

mydf <- structure(list(X = c(0.0122, 0.0121, 0.0121, 0.0121, 0.0121, 
    0.0121, 0.0121), Y = c(NA, NA, 0.027, 0.027, 0.028, 0.028, 0.028)), 
   .Names = c("X", "Y"), class = "data.frame", row.names = c(NA, -7L))

mydf
#        X     Y
# 1 0.0122    NA
# 2 0.0121    NA
# 3 0.0121 0.027
# 4 0.0121 0.027
# 5 0.0121 0.028
# 6 0.0121 0.028
# 7 0.0121 0.028

Upvotes: 8

Related Questions