2

我正在尝试计算 tibble 上的滚动相关性,在循环中遍历列名。不过,我似乎在努力将变量传递给函数。这有效:

tbl <- tibble(date = seq(as.Date("1983-03-31"), by=7, length.out=100), 
    col1 = 1:100, col2 = sample(100, size = 100, replace=TRUE), col3 = col1 + col2)
tbl %>% 
    tq_mutate_xy(
        x = col1,
        y = col3,
        mutate_fun = runCor,
        n = 10,
        use = "pairwise.complete.obs",
        col_rename = "col1_col3_corr"
      )

但这不会:

tbl <- tibble(date = seq(as.Date("1983-03-31"), by=7, length.out=100), 
    col1 = 1:100, col2 = sample(100, size = 100, replace=TRUE), col3 = col1 + col2)
c1 <- "col1"
c2 <- "col3"
tbl %>% 
    tq_mutate_xy(
        x = !!c1,
        y = !!c2,
        mutate_fun = runCor,
        n = 10,
        use = "pairwise.complete.obs",
        col_rename = paste0(c1, "_", c2, "_corr")
    )

错误是“check_x_y_valid(data, x, y) 中的错误:x = !(!c1) 不是有效名称。”

我究竟做错了什么?

4

1 回答 1

3

首先,我认为您想要非标准评估 (NSE) 版本tq_mutate_xy- 即tq_mutate_xy_. 因此,当你使用这些函数的 NSE 时,你需要使用字符串——这意味着你的mutate_fun变量也应该是一个字符串。以下应该有效:

c1 <- "col1"
c2 <- "col3"
tbl %>% 
  tq_mutate_xy_(
    x = c1,
    y = c2,
    mutate_fun = "runCor",
    n = 10,
    use = "pairwise.complete.obs",
    col_rename = paste0(c1, "_", c2, "_corr")
  )

请务必查看帮助文档中的示例 5,?tq_mutate_xy

于 2018-04-12T16:01:36.517 回答