本文介绍了按组从上一行中减去值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在R中,假设我有此数据框:
In R, let's say I have this data frame:
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日期从当前值中减去先前的值,以创建此值:
And I want to subtract the previous value from the current value, by group ID date, to create this:
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)))
为清楚起见,您可以按date
和分组列进行arrange
(按照,由律师)
For clarity you can arrange
by date
and grouping column (as per comment by lawyer)
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]
这篇关于按组从上一行中减去值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!