R - 遍历每一行并填充前一行的值

时间:2013-02-15 17:33:42

标签: r loops

我想测试特定列中的值是否包含NA值,如果是,请使用上一行中的值填充该NA空间。我仍然试图了解apply系列函数。

E.g。我想转此:

      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

2 个答案:

答案 0 :(得分:7)

这是来自zoo包的na.locf函数的任务。见?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

答案 1 :(得分:5)

data.tableroll = 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