R dplyr滞后的年变化率(增长率) [英] R annual rate of change (growth rate) with dplyr lag

查看:86
本文介绍了R dplyr滞后的年变化率(增长率)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一种简单的方法来计算R中变量的年变化率,而不是时间序列(例如GDP,通货膨胀等)?

What is a simple way to calculate the annual rate of change of a variable in R, that is not a time series (for example GDP, Inflation, etc)?

推荐答案

软件包 dplyr 有助于其 lag()函数,不适用于ts(时间序列)数据帧。下面是一个示例:

The package dplyr helps with its lag() function, that is not for a ts (time series) data frame. Here an example:

#using the library "dplyr"
library(dplyr)
#setting seed
set.seed(20)
#creating a random dataframe
df <- data.frame(date=paste(rep(2000:2017, each=4),"Q",rep(1:4, 18)), GDP= cumsum(sample(c(-0.5, 3), 72, TRUE)))
#calculating the annual percentage change
df <- df %>% mutate(change=(GDP-lag(GDP,4))/lag(GDP,4)*100)

对于月度数据,只需设置: lag(VAR,12)其中VAR代表感兴趣的变量

In case of monthly data, simply set: lag(VAR,12) where VAR stands for the variable of interest

这篇关于R dplyr滞后的年变化率(增长率)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆