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

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

问题描述

我觉得这在基础 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 将当前行的百分比加到下一行向下,并几乎以累积方式滚动.

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.

谢谢.

推荐答案

filter() 函数stats 包的一部分,它是基于 R 的.保留一位小数:

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天全站免登陆