将函数应用于指定范围;变化率 [英] Apply a function to a specified range; Rate of Change

查看:68
本文介绍了将函数应用于指定范围;变化率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
计算R中的移动平均值

Possible Duplicate:
Calculating moving average in R

我已经在R中编写了变化率函数,定义为:

I have written a rate of change function in R, defined as:

rateChange <- function(x) ((last(x)-first(x))/first(x))*100

它在各种日期范围(例如5天,10天,200天等的变化率)上都可以很好地工作.但是,我现在必须每天都应用此功能.例如,要确定5天的变化率,则需要对过去6次数据进行观察.

It works wonderfully on various date ranges, such as the rate of change for 5 days, 10 days, 200 days, etc. However, I now have need to apply this function between every day. For example, to identify the rate of change for 5 days one would require the past 6 data observations.

这里是Excel中的一个示例,为清楚起见,我试图重现变更率"列:

Here is an example in Excel, and for clarity, I am trying to reproduce the "Rate of Change" column:

谢谢!

推荐答案

我建议使用TTR::ROC:

library(TTR)
roc <- c(18.89, 18.93, 18.55, 18.77, 18.87, 18.91)
ROC(roc, type="discrete")*100
# [1]         NA  0.2117522 -2.0073957  1.1859838  0.5327651  0.2119767

这篇关于将函数应用于指定范围;变化率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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