0

我正在尝试更多地了解如何优化重复操作。

我创建了以下示例,它生成一个随机的小时间序列数据框来绘制 3 个不同变量的滚动 7 天平均值:

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")

但是,当我运行它时,我收到错误消息:

roll_avg_7(., n3) 中的错误:未使用的参数 (n3)

我已经阅读了几个关于未使用参数的不同线程,但我无法理解为什么它不起作用。

4

0 回答 0