2 years ago
#1529
Ollie
Custom function returning unused argument
I am trying to learn a little more about how to optimize repeated operations.
I have created the following example which generates a random little time series data frame to plot the rolling 7-day average for 3 different variables:
library(tidyverse)
library(tidyquant)
library(lubridate)
# generate random time series data
df <- tibble(date = seq(ymd("2020-07-01"), by = "days", length.out = 50), n1 = sample(1:100, 50, replace = TRUE), n2 = sample(1:100, 50, replace = TRUE), n3 = sample(1:100, 50, replace = TRUE))
# trying to create custom function to generate rolling 7 day average and add as new column
roll_avg_7 <- function(x) {
tq_mutate(
select = x,
mutate_fun = rollapply,
width = 7,
align = "right",
FUN = mean,
na.rm = TRUE,
col_rename = paste0(x, "_mean_7")
)
}
# trying to apply custom function sequentially to each n column to create new df
df2 <- df %>%
roll_avg_7(n1) %>%
roll_avg_7(n2) %>%
roll_avg_7(n3)
# plot the rolling averages for each n variable
ggplot(df2, aes(date)) +
geom_line(aes(y=n1_mean_7), colour = "red") +
geom_line(aes(y=n2_mean_7), colour = "blue") +
geom_line(aes(y=n3_mean_7), colour = "green")
However when I run this I get the error message:
Error in roll_avg_7(., n3) : unused argument (n3)
I have read several different threads about unused arguments but just cannot get my head around why it isn't working.
r
tidyquant
0 Answers
Your Answer