滚动百分比沿列添加 [英] Rolling percentage add along column

查看:76
本文介绍了滚动百分比沿列添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得在R底下应该很容易,但是我无法弄清楚. 我有一个简单的数据框,让我们说它看起来像这样

I feel this should be easy in base R but I just can't figure it out. I have a simple dataframe, let's say it looks like this

tbl <-  read.table(text = 
    "Field1 Field2
    100 200
    150 180
    200 160
    280 250
    300 300
    300 250",
header = TRUE)

现在,我想做的是创建一个函数,该函数将应用滚动%的加法,例如:

Now, what I want to do is create a function that will apply a rolling % addition, something like:

fn <- function(tbl, pct) {}

接受上面的数据框为tbl.它将根据pct将当前行的一个百分比分数添加到NEXT行中,并以累积的方式滚动.

which accepts the dataframe above as tbl. It adds a percentage fraction of the current row to the NEXT row down based on pct, and rolls this almost in a cumulative fashion.

例如,fn(tbl$Field1, 0.1)将产生以下结果:

For example, fn(tbl$Field1, 0.1) would generate the following results:

100   (100 + 0.1*0)
160   (150 + 0.1*100 = 160)
216   (200 + 0.1*160 = 216)
301.6 (280 + 0.1*216 = 301.6)

我会使用打包解决方案,但希望使用基数R,因为它有助于学习过程!我的长期目标是建立一个遍历field和pct每种组合的循环过程,以便我可以在回归模型中测试其效果;因此,我的直觉是前进的道路是我以后可以应用的功能.

I'd use a package solution, but would prefer base R as it helps with the learning process! My longer term goal is to build a process the loops through each combination of field and pct so I can test it's effect in a regression model; hence my gut feel is that a function I can later apply is the way forward.

谢谢.

推荐答案

The filter() function is part of the stats package, which is base R. Keeping to one decimal place:

round(filter(tbl$Field1, 0.1, method="recursive"), 1)

会产生以下结果

100.0 160.0 216.0 301.6 330.2 333.0

这篇关于滚动百分比沿列添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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