3

I have a dataframe like this:

df <- data.frame(width = c(1,2,2,4), values = c(10,11,13,20))

I want to use rollapply to compound the 'values' column, but I want to use a variable width for each row, getting the width from the appropriate row in the 'width' column.

For the life of me I can't figure out how to pass the width parameter as a variable from the 'width' column.

I have a solution using dplyr's mutate, but it's clunky and very slow. Below is my current code, with a static '3' in place of the value I'd like to sub in:

rollapply(df[ , values_column], width = 3, function(x) rolling_compounder(x),
                                align = "right", fill = NA, partial = FALSE, by.column = FALSE)

EDIT:

Using decimal values: 0.1, 0.11, 0.13, 0.2

And the same widths as above, I would expect the compounded results to be:

0.1, 0.221, 0.254, 0.656

Jaap
  • 81,064
  • 34
  • 182
  • 193
sotiris
  • 63
  • 1
  • 1
  • 8
  • Expected output? (Love your name) :) – Sotos Oct 13 '17 at 13:58
  • Thanks. Love yours too. Added the expectation in the question. – sotiris Oct 13 '17 at 14:11
  • What about `rollapplyr(df$values, width = df$width, sum)`? – Jaap Oct 13 '17 at 14:21
  • Thanks Jaap. That works! Unfortunately, I'm passing the width column name as a variable too. Sorry, should have mentioned this before. So when I use the syntax width = df[, mycol_name_variable] it doesn't work. Any ideas please? – sotiris Oct 13 '17 at 14:37
  • No worries, Japp. I figured it out, I rename the column to something static before running the rollapply function. Thanks so much for all your help. – sotiris Oct 13 '17 at 14:48
  • If you want to apply it to more than one column, you could do: `lapply(df[2:3], function(x) rollapplyr(x, width = df$w, sum))` – Jaap Oct 13 '17 at 14:51

0 Answers0