I would like to compute all (or at least many) fixed window averages using dplyr and RcppRoll. For example, if I want to compute the average wind speed from the storms
data for the previous 4, 5, and 6 timesteps, I can use the following:
library(dplyr)
library(RcppRoll)
set.seed(1)
storms <- storms[storms$name %in% sample(storms$name, size = 4),]
storms %>%
select(name, year, month, day, hour, wind) %>%
group_by(name) %>%
arrange(name, year, month, day, hour) %>%
mutate_at("wind", .funs = funs(
"avg_4" = roll_meanr(., n = 4, fill = NA),
"avg_5" = roll_meanr(., n = 5, fill = NA),
"avg_6" = roll_meanr(., n = 6, fill = NA)
))
This works, however if I wanted to compute all of the fixed window averages for windows of 2 through 20, I'd get tired of copying and pasting the rows inside of funs()
.
It seems like I should be able to parameterize this somehow, but I haven't yet figured out how.
Using Base R, I hope it help:
Just use the power of quoting and unquoting! That's what you have:
Now let's make a function that builds a bunch of expressions like
roll_meanr(x, n)
for differentx
s andn
s.All the magic comes from
rlang::expr(RcppRoll::roll_meanr(!!.var, !!(.nn)))
. With!!.var
you substitute.var
with input variable name, i.e.wind
. With!!.nn
you substitute.nn
with number. Next, you quote the expression withrlang::expr(...)
.This function gets variable names without
""
and vector of window sizes. Output looks like this:You can see expressions you are looking for.
Next, you can put
make_rollmeans
insidemutate()
call using!!!
(bang-bang-bang) operator for unquoting expressions built by it.I hope the result is the same as you are asked for. :)