3

我的数据具有这种格式和名为 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 并删除它们?

4

2 回答 2

3
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)
于 2013-06-01T19:10:56.620 回答
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

也许还有其他问题?

于 2013-06-01T18:08:42.097 回答