2

我正在尝试从 data.frame 的底部到 data.frame 的顶部运行 rollapply。基本上,data.frame (RBH) 中的最后一行是 2012 年给定主题的最终测量值。然后我需要减去前几年的每个年度测量值,以计算个人每年的大小。

示例数据帧:

df1 <- structure(c(1.62, 3.96, 4.89, 6.61, 8.79, 
                   57.15, 2.43, 5.58, 7.2, 9.3, 
                   11.87, 66.6, 1.47, 3.49, 4.32,
                   NA, NA, 60.75),
                 .Dim = c(6L, 3L),
                 .Dimnames = list(c("2008", "2009", "2010","2011", "2012","RBH"),
                                  c("Tree001", "Tree002", "Tree003")))

预期输出:

Tree001 <- c(31.28, 32.90, 36.86, 41.75, 48.36, 57.15)    
Tree002 <- c(29.62, 32.05, 37.63, 44.83, 54.13, 66.00)    
Tree003 <- c(51.47, 52.94, 56.43, 60.75, NA, NA)    
df2 <- data.frame(Tree001, Tree002, Tree003)    
rownames(df2) <- 2007:2012    

我已经尝试从我在Rollapply() 中找到的建议向后运行 rollapply R,但我没有得到预期的输出。它以列表而不是 data.frame 的形式出现,并从当前单元格中减去每个值,而不是从运行值中减去。

我试过的代码:

if ( !require(zoo) ) print(" Need pkg:zoo for rollapply")
df3 <- rollapply(df1[length(df1):1], width=2, diff, fill=NA, partial=T)    
df3    
 [1]     NA     NA     NA  -0.83  -2.02  65.13 -54.73  -2.57  -2.10  -1.62    
[11]  -3.15  54.72 -48.36  -2.18  -1.72  -0.93  -2.34     NA

任何建议,将不胜感激。

4

1 回答 1

2

这更接近你想要的:

df1[is.na(df1)] = 0 ##This is how you're actually treating it!
df1 = data.frame(df1)


> df2 = apply(df1[nrow(df1):1,], 2, function(x) c(x[1], x[1]-cumsum(x[-1])))
> df2 = df2[nrow(df2):1,]
> df2
     Tree001 Tree002 Tree003
2008   31.28   30.22   51.47
2009   32.90   32.65   52.94
2010   36.86   38.23   56.43
2011   41.75   45.43   60.75
2012   48.36   54.73   60.75
RBH    57.15   66.60   60.75
于 2014-07-30T17:14:44.887 回答