填充数据框中的特定列

时间:2013-06-01 17:54:49

标签: r

我的数据有这种格式,而且框架名为ex:

Day                  value1         value2
12-12-2012 00:00:00  1                 1
12-12-2012 00:00:02  NA                2
12-12-2012 00:00:03  1                 NA
12-12-2012 00:00:04  NA                4
12-12-2012 00:00:00  2                 1
12-12-2012 00:00:02  NA                2
12-12-2012 00:00:03  2                 NA
12-12-2012 00:00:04  NA                4

我想要的输出是:

Day                 value1         value2
12-12-2012 00:00:00  1                  1
12-12-2012 00:00:02  1                  2
12-12-2012 00:00:03  1                  NA
12-12-2012 00:00:04  1                  4
12-12-2012 00:00:00  2                  1
12-12-2012 00:00:02  2                  2
12-12-2012 00:00:03  2                  NA
12-12-2012 00:00:04  2                  4

我尝试了什么:

fl = na.locf(ex$value1)

但问题是删除value2。如何在具有多个列的框架中的特定列中使用na.locf并删除它们?

2 个答案:

答案 0 :(得分:2)

require(zoo)

dat <- read.table(text="
Day                  value1         value2
12-12-2012 00:00:00  1                 1
12-12-2012 00:00:02  NA                2
12-12-2012 00:00:03  1                 NA
12-12-2012 00:00:04  NA                4
12-12-2012 00:00:00  2                 1
12-12-2012 00:00:02  NA                2
12-12-2012 00:00:03  2                 NA
12-12-2012 00:00:04  NA                4",header=TRUE, row.names=NULL)

dat$value1 <- na.locf(dat$value1)

答案 1 :(得分:1)

我试图重现您的问题,但对我来说,您建议的解决方案可以按照您的意愿运作。

> require(zoo)
> ex <-data.frame(
    Day =c("12-12-2012 00:00:00","12-12-2012 00:00:02","12-12-2012 00:00:03","12-12-2012 00:00:04","12-12-2012 00:00:00","12-12-2012 00:00:02","12-12-2012 00:00:03","12-12-2012 00:00:04"), 
    value1 = c(1,NA,1,NA,2,NA,2,NA), 
    value2 = c(1,2,3,4,1,2,3,4))
> fl = na.locf(ex)
> fl
                  Day value1 value2
1 12-12-2012 00:00:00      1      1
2 12-12-2012 00:00:02      1      2
3 12-12-2012 00:00:03      1      3
4 12-12-2012 00:00:04      1      4
5 12-12-2012 00:00:00      2      1
6 12-12-2012 00:00:02      2      2
7 12-12-2012 00:00:03      2      3
8 12-12-2012 00:00:04      2      4

也许还有别的东西出错了?