我有一个 R 数据框,例如:
df <- data.frame(period=rep(1:4,2),
farm=c(rep('A',4),rep('B',4)),
cumVol=c(1,5,15,31,10,12,16,24),
other = 1:8);
period farm cumVol other
1 1 A 1 1
2 2 A 5 2
3 3 A 15 3
4 4 A 31 4
5 1 B 10 5
6 2 B 12 6
7 3 B 16 7
8 4 B 24 8
我如何在每个时间段内找到每个农场累计体积的变化,忽略“其他”列?我想得到以下数据框(可选择保留cumVol列):
如何在每个周期中查找每个农场的cumVol变化,而忽略“other”列?我希望获得类似于以下数据框的结果(如果需要,可以包含cumVol列):
period farm volume other
1 1 A 0 1
2 2 A 4 2
3 3 A 10 3
4 4 A 16 4
5 1 B 0 5
6 2 B 2 6
7 3 B 4 7
8 4 B 8 8
在实践中,可能会有许多类似于“农场”的列,以及许多类似于“其他”的(即被忽略的)列。我希望能够使用变量指定所有列名。
我正在使用dplyr包。
with(df, ave(cumVol,farm,FUN=function(x) c(0,diff(x))) )
。 - thelatemail