在R中,假设我有以下数据框:Dataid date value2380 10/30/12 21.012380 10/31/12 22.042380 11/1/12 22.652380 11/2/12 23.1120100 10/30/12 35.2120100 10/31/12 37.0720100 11/1/12 38.1720100 11/2/12 38.9720103 10/30/12 57.9820103 10/31/12 60.83 我想按组ID日期从当前值中减去先前的值,以创建此值:id date value diff2380 10/30/12 21.01 02380 10/31/12 22.04 1.032380 11/1/12 22.65 0.612380 11/2/12 23.11 0.4620100 10/30/12 35.21 020100 10/31/12 37.07 1.8620100 11/1/12 38.17 1.120100 11/2/12 38.97 0.820103 10/30/12 57.98 020103 10/31/12 60.83 2.85
2 回答
阿晨1998
TA贡献2037条经验 获得超6个赞
与dplyr:
library(dplyr)
data %>%
group_by(id) %>%
arrange(date) %>%
mutate(diff = value - lag(value, default = first(value)))
为了清楚起见,你可以arrange通过date和分组列(根据评论的律师)
data %>%
group_by(id) %>%
arrange(date, .by_group = TRUE) %>%
mutate(diff = value - lag(value, default = first(value)))
或lag搭配order_by:
data %>%
group_by(id) %>%
mutate(diff = value - lag(value, default = first(value), order_by = date))
与data.table:
library(data.table)
dt <- as.data.table(data)
setkey(dt, id, date)
dt[, diff := value - shift(value, fill = first(value)), by = id]
- 2 回答
- 0 关注
- 655 浏览
添加回答
举报
0/150
提交
取消