gpt4 book ai didi

r - 我如何在 R 中区分面板数据

转载 作者:行者123 更新时间:2023-12-01 09:26:33 25 4
gpt4 key购买 nike

我想知道是否有任何简单的 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

最佳答案

大街

transform(MyData, P1d = ave(Price, Good, FUN = function(x) c(NA, diff(x))))

大道/gsubfn

最后一个解决方案可以使用 fn$ 稍微缩短在 gsubfn 包中:
library(gsubfn)
transform(MyData, P1d = fn$ave(Price, Good, FUN = ~ c(NA, diff(x))))

dplyr
library(dplyr)

MyData %>%
group_by(Good) %>%
mutate(P1d = Price - lag(Price)) %>%
ungroup

数据表
library(data.table)

dt <- data.table(MyData)
dt[, P1d := c(NA, diff(Price)), by = Good]

更新

dplyr 现在使用 %>%而不是 %.% .

关于r - 我如何在 R 中区分面板数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22558084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com