gpt4 book ai didi

r - 按组从前一行减去值

转载 作者:行者123 更新时间:2023-12-03 10:31:47 25 4
gpt4 key购买 nike

在 R 中,假设我有这个数据框:

Data
id date value
2380 10/30/12 21.01
2380 10/31/12 22.04
2380 11/1/12 22.65
2380 11/2/12 23.11
20100 10/30/12 35.21
20100 10/31/12 37.07
20100 11/1/12 38.17
20100 11/2/12 38.97
20103 10/30/12 57.98
20103 10/31/12 60.83

我想从当前值中减去以前的值,按组 ID 日期来创建:
id      date        value   diff
2380 10/30/12 21.01 0
2380 10/31/12 22.04 1.03
2380 11/1/12 22.65 0.61
2380 11/2/12 23.11 0.46
20100 10/30/12 35.21 0
20100 10/31/12 37.07 1.86
20100 11/1/12 38.17 1.1
20100 11/2/12 38.97 0.8
20103 10/30/12 57.98 0
20103 10/31/12 60.83 2.85

最佳答案

dplyr :

library(dplyr)

data %>%
group_by(id) %>%
arrange(date) %>%
mutate(diff = value - lag(value, default = first(value)))

为清楚起见,您可以 arrange来自 date和分组列(根据 comment by lawyer )

data %>%
group_by(id) %>%
arrange(date, .by_group = TRUE) %>%
mutate(diff = value - lag(value, default = first(value)))

lagorder_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]

关于r - 按组从前一行减去值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30606360/

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