[英]Grouped percent change in R data.table
I'd like to calculate the % diff in subsequent observations of an R data.table
, grouping by a variable. 我想在R data.table
后续观察中计算diff的data.table
,按变量分组。 For example, given a dataset like this: 例如,给定这样的数据集:
dt <- data.table(group=c(rep("A", 3), rep("B", 3)),
index=rep(1:3, 2),
val=1:6)
# group index val
# 1: A 1 1
# 2: A 2 2
# 3: A 3 3
# 4: B 1 4
# 5: B 2 5
# 6: B 3 6
I'd like a result like this, calculating % diff of val
(first record goes from 1->2, so 100%, second 2->3 so 50% diff, etc.): 我想要这样的结果,计算val
%diff(第一条记录来自1-> 2,因此为100%,第二条2-> 3为50%,等等):
# group index pct.diff
# 1: A 1 1.00
# 2: A 2 0.50
# 3: B 1 0.25
# 4: B 2 0.20
You can use diff
and .N
to remove the final record in each group: 您可以使用diff
和.N
删除每个组中的最终记录:
dt[, list(index=index[-.N],
pct.diff=diff(val) / val[-.N]),
group]
This produces the result at the bottom of the question. 这将在问题的底部产生结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.