我正在尝试计算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")
)
错误是&#34; check_x_y_valid(data,x,y)出错:x =!(!c1)不是有效名称。&#34;
我做错了什么?
答案 0 :(得分:3)
首先,我认为你想要tq_mutate_xy
的非标准评估(NSE)版本 -
也就是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")
)
请务必查看帮助文档?tq_mutate_xy