我想知道是否有任何简单的 R 命令或包都可以让我轻松地将变量添加到 data.frames,这些变量是这些变量的“差异”或随时间的变化。
如果我的数据如下所示:
set.seed(1)
MyData <- data.frame(Day=0:9 %% 5+1,
Price=rpois(10,10),
Good=rep(c("apples","oranges"), each=5))
MyData
Day Price Good
1 1 8 apples
2 2 10 apples
3 3 7 apples
4 4 11 apples
5 5 14 apples
6 1 12 oranges
7 2 11 oranges
8 3 9 oranges
9 4 14 oranges
10 5 11 oranges
然后在对价格变量进行“一阶差分”之后,我的数据将如下所示。
Day Price Good P1d
1 1 8 apples NA
2 2 10 apples 2
3 3 7 apples -3
4 4 11 apples 4
5 5 14 apples 3
6 1 12 oranges NA
7 2 11 oranges -1
8 3 9 oranges -2
9 4 14 oranges 5
10 5 11 oranges -3