5

我想测试来自特定列的值是否包含 NA 值,如果是,则用前一行的值填充该 NA 空间。我仍在尝试掌握apply函数系列的窍门。

例如我想把这个:

      Date   Balance
2012-01-01      1000
2012-01-02        NA
2012-01-03        NA
2012-01-04      1200
2012-01-05      1215
2012-01-06        NA

进入:

      Date   Balance
2012-01-01      1000
2012-01-02      1000
2012-01-03      1000
2012-01-04      1200
2012-01-05      1215
2012-01-06      1215
4

2 回答 2

7

这是na.locfzoo 包中的功能任务。看?na.locf

考虑一下DF你的data.frame,然后:

DF <- read.table(text="      Date   Balance
2012-01-01      1000
2012-01-02        NA
2012-01-03        NA
2012-01-04      1200
2012-01-05      1215
2012-01-06        NA", header=TRUE)

library(zoo)
na.locf(DF)
        Date Balance
1 2012-01-01    1000
2 2012-01-02    1000
3 2012-01-03    1000
4 2012-01-04    1200
5 2012-01-05    1215
6 2012-01-06    1215
于 2013-02-15T17:36:57.883 回答
5

使用data.tablewithroll = TRUE也能很好地做到这一点!

require(data.table)
# convert Date column to date format
df$Date <- as.Date(df$Date)
# keep this, as we'll remove rows with NA to use `roll`
dates   <- df$Date
# remove rows with NA
dt2     <- na.omit(data.table(df))
# set key to Date
setkey(dt2, "Date")
# use dates which has the NA rows that will be filled 
# with value from previous column with roll=T
dt2[J(dates), roll=T]

#          Date Balance
# 1: 2012-01-01    1000
# 2: 2012-01-02    1000
# 3: 2012-01-03    1000
# 4: 2012-01-04    1200
# 5: 2012-01-05    1215
# 6: 2012-01-06    1215
于 2013-02-15T18:32:07.270 回答