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

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

问题描述

可能的重复:
计算 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天全站免登陆