问题
I'm trying to run rollapply from the bottom of my data.frame up to the top of my data.frame. Basically the last row in the data.frame (RBH) is the final measurement for a given subject in 2012. I then need to subtract each annual measurement in the previous years to calculate what the individual's size would have been each year prior.
Sample data.frame:
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")))
Intended output:
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
I've tried running rollapply backwards from a suggestion I found at Rollapply() backwards in R , but I didn't get the intended output. It came out as a list instead of a data.frame, and subtracted each value from the current cell, not from the running value.
Code I tried:
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
Any suggestions would be appreciated.
回答1:
This is closer to what you want:
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
来源:https://stackoverflow.com/questions/25042230/r-rollapply-bottom-to-top