如何修改代码,以便在函数内进行调用时可以将变量列表传递给select
中的tq_mutate
?
以下代码在函数外部调用时有效,但在函数内部调用时无效:
(编辑后添加了可复制的示例):
library(tidyquant)
# WORKS
x <- data_frame(date=seq(as.Date('2018-01-01'),as.Date('2018-01-10'),by=1), a=seq(1,10,by=1), b=seq(11,20,by=1))
k=c(1,2)
lag_cols <- c('a', 'b')
temp_names <- crossing(lag_cols, k)
temp_names <- temp_names %>% arrange(k, lag_cols)
col_names <- paste0(temp_names$lag_cols, '_lag', temp_names$k)
result <- x %>% tq_mutate(
select = c('a', 'b'),
mutate_fun = lag.xts,
k = k,
col_rename=col_names)
result
# DOESN'T WORK
lag_data <- function(df, k) {
lag_cols_in <- c('a', 'b')
temp_names <- crossing(lag_cols_in, k)
temp_names <- temp_names %>% arrange(k, lag_cols_in)
col_names <- paste0(temp_names$lag_cols_in, '_lag', temp_names$k)
df %>% tq_mutate(
select = lag_cols_in,
mutate_fun = lag.xts,
k = k,
col_rename=col_names)
}
我的阅读表明,在函数内部调用tq_mutate时使用select_
,因此我需要将.dots=c('a','b','c')
调用传递给select
。
如何修改代码,以便传递变量列表?请注意,在两种情况下,都可以将select=c('a', 'b')
放入tq_mutate调用中,因此我猜测这与环境和变量作用域有关。
这是错误消息:
Error in .f(.x[[i]], ...) : object 'lag_cols_in' not found
23.
.f(.x[[i]], ...)
22.
map(.x[sel], .f, ...)
21.
map_if(quos, !is_helper, eval_tidy, mask)
20.
vars_select_eval(.vars, quos)
19.
tidyselect::vars_select(names(.data), !!!quos(...))
18.
select.data.frame(.data, !!!dots)
17.
select(.data, !!!dots)
16.
select_.data.frame(data, select)
15.
dplyr::select_(data, select)
14.
tq_transmute_.tbl_df(data = data, select = select, mutate_fun = mutate_fun, col_rename = col_rename, ... = ...)
13.
tq_transmute_(data = data, select = select, mutate_fun = mutate_fun, col_rename = col_rename, ... = ...)
12.
tq_mutate_.tbl_df(data = data, select = lazyeval::expr_text(select), mutate_fun = lazyeval::expr_text(mutate_fun), col_rename = col_rename, ... = ...)
11.
tq_mutate_(data = data, select = lazyeval::expr_text(select), mutate_fun = lazyeval::expr_text(mutate_fun), col_rename = col_rename, ... = ...)
10.
tq_mutate(., select = lag_cols_in, mutate_fun = lag.xts, k = k, col_rename = col_names)
9.
function_list[[k]](value)
8.
withVisible(function_list[[k]](value))
7.
freduce(value, `_function_list`)
6.
`_fseq`(`_lhs`)
5.
eval(quote(`_fseq`(`_lhs`)), env, env)
4.
eval(quote(`_fseq`(`_lhs`)), env, env)
3.
withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
2.
df %>% tq_mutate(select = lag_cols_in, mutate_fun = lag.xts, k = k, col_rename = col_names)
1.
lag_data(x, k)
答案 0 :(得分:0)
也许有更好的方法,但这似乎行得通...
library(tidyquant)
x <- data_frame(date=seq(as.Date('2018-01-01'),as.Date('2018-01-10'),by=1), a=seq(1,10,by=1), b=seq(11,20,by=1))
k <- c(1,2)
lag_data <- function(df, k) {
lag_cols_in <- c('a', 'b')
temp_names <- crossing(lag_cols_in, k)
temp_names <- temp_names %>% arrange(k, lag_cols_in)
col_names <- paste0(temp_names$lag_cols_in, '_lag', temp_names$k)
df %>% tq_mutate(
select = lag_cols_in[1:length(lag_cols_in)],
mutate_fun = lag.xts,
k = k,
col_rename = col_names)
}
lag_data(x,k)