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) {}
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.
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)
etc.
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.
Thanks.