2013-06-01 126 views
2

我的數據有這樣的格式和命名的前框:填充特定列的數據幀

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並刪除它們?

+0

locf是以前的值 –

回答

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

我試圖重現您的問題,但對於我來說,您建議的解決方案可以按照您的期望工作。

> 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 

也許別的東西是錯誤的?