2012-12-21 96 views
1

這是Subtract previous year's from value from each grouped row in data frame的擴展。使用plyr的選項非常有意義。R數據幀:行間計算

現在,我想添加更多的列。我也修改了一年,所以這是一個具有不同起點的實際年份。這裏是一個鏈接到製表符分隔DF:https://dl.dropbox.com/u/9699533/df.txt

enter image description here

我無法得到一個指向上一行時,我當前行中我。我想把它傳遞給plyr :: transform的函數部分。我該如何寫這個?謝謝!

備用數據框中輸入〜

> dput(df) 
structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 
4L, 4L, 5L, 5L, 5L), value = c(6L, 16L, 21L, 5L, 10L, 26L, 2L, 
12L, 26L, 9L, 16L, 26L, 2L, 15L, 29L), year = c(2007L, 2008L, 
2009L, 2011L, 2012L, 2013L, 2004L, 2004L, 2006L, 2010L, 2011L, 
2012L, 2014L, 2015L, 2016L), actual = c(6L, 10L, 5L, 5L, 5L, 
16L, 2L, 10L, 14L, 9L, 7L, 10L, 2L, 13L, 14L)), .Names = c("id", 
"value", "year", "actual"), class = "data.frame", row.names = c(NA, 
-15L)) 

回答

3

不要使用transform

foo <- function(x){ 
    x$ratio <- c(NA,tail(x$actual,-1)/head(x$value,-1)) 
    x 
} 
> 
> ddply(df,.(id),foo) 
    id value year actual  ratio 
1 1  6 2007  6  NA 
2 1 16 2008  10 1.6666667 
3 1 21 2009  5 0.3125000 
4 2  5 2011  5  NA 
5 2 10 2012  5 1.0000000 
6 2 26 2013  16 1.6000000 
7 3  2 2004  2  NA 
8 3 12 2004  10 5.0000000 
9 3 26 2006  14 1.1666667 
10 4  9 2010  9  NA 
11 4 16 2011  7 0.7777778 
12 4 26 2012  10 0.6250000 
13 5  2 2014  2  NA 
14 5 15 2015  13 6.5000000 
15 5 29 2016  14 0.9333333 

如果我們可以假設你的數據幀進行排序,而且我們知道每個組有多大(由id)是,我們甚至不需要做全裂應用於件事:

df$ratio2 <- with(df,c(NA,tail(actual,-1)/head(value,-1))) 
df$ratio2[seq(1,nrow(df),by = 3)] <- NA 
+0

謝謝,喬蘭。這些羣體的大小可能不相同。所以,我會堅持ddply。如何seq列?該集是有序的。 – user1100825

+0

把'x $ seq < - seq_along(x $ id) - 1'放入'foo'中? – joran

+0

謝謝,喬蘭。我得到了這個工作。 – user1100825