问题描述
虽然我发现了几个类似的问题,但我无法在基础 R 中找到解决我的问题的简单方法.我想从一组数据(此处为 y 值)计算 yoy 百分比变化,并将此Delta"系列作为新列添加到我的数据框中.
though I have found several similar questions, I could not find a simple solution to my problem in base R.I want to calculate the yoy percentage change from a set of data (here the y value) and add this "Delta"-series as a new column to my data frame.
例如:
>x = c(2000,2001,2002,2003,2004,2005,2006)
>y = c(100,104,106,108,112,115,121)
>df = data.frame(x,y)
如果我通过读取 .csv 文件加载数据该怎么办?我是否必须将此数据转换为数据框?
And what to do if I load my data by reading a .csv file? Do i have to convert this data to a data frame?
推荐答案
data.table_1.9.5 引入了新函数 shift
,默认为 type='lag'
和 n=1L
.如果需要更改,您可以指定这些参数.setDT
将 data.frame
转换为 data.table
,基于标准 (y/shift(y)...
)
data.table_1.9.5 introduced new function shift
, which by default will be type='lag'
and n=1L
. You could specify those arguments, if you need to change. setDT
converts data.frame
to data.table
, a new column is created (:=
) based on the criteria (y/shift(y)...
)
library(data.table)
setDT(df)[, new.col := y/shift(y) - 1]
或者在基础 R 中(来自@David Arenburg 的评论)
Or in base R (from @David Arenburg's comments)
transform(df, new.col=c(NA,y[-1]/y[-nrow(df)]-1))
这篇关于R 的同比百分比变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!