【发布时间】:2018-12-12 00:02:05
【问题描述】:
我正在尝试创建一段非常程序化的代码,让我可以根据我提交给函数的模型公式来获取模型变量。我需要的一些功能必须即时计算。我不知道如何做其中的一些。我快到了,但需要弄清楚最后一点。这是我的代表:
让我们使用mtcars 数据集。现在我设置它的方式我已经以编程方式定义了一些我想成为新列的函数。例如,这有效:
# everything below I've defined programmatically:
cyl_lag_2 <- function(x) lag(x, 2)
cyl_lag_3 <- function(x) lag(x, 3)
lag_model_vars <- c("cyl_lag_2", "cyl_lag_3")
stem_col <- function(.f, ...) .f(...)
# here I apply these to the dataset by hard-coding the lag column in two ways
# this works
mtcars %>%
mutate_at(lag_model_vars, funs(stem_col(., cyl)))
# also this does
mtcars %>%
mutate_at(lag_model_vars, funs(stem_col(., .data[["cyl"]])))
但我的问题是,如果我希望它引用多个列怎么办?例如:
# everything below I've defined programmatically:
cyl_lag_2 <- function(x) lag(x, 2)
hp_lag_3 <- function(x) lag(x, 3)
lag_model_vars <- c("cyl_lag_2", "hp_lag_3")
lag_cols <- sub("(.*?)_(.*)", "\\1", c("cyl_lag_2", "hp_lag_3"))
stem_col <- function(.f, ...) .f(...)
# this does not work at all
mtcars %>%
mutate_at(lag_model_vars, funs(stem_col(., .data[[lag_cols]])))
# nor this
mtcars %>%
mutate_at(lag_model_vars,
funs(stem_col(., .data[[sub("(.*?)_(.*)", "\\1", expr(.))]])))
想法?我觉得我很接近了。如果传入的数据帧被分组,该解决方案也应该有效,因此不能接受 mtcars。
mtcars %>%
mutate_at(lag_model_vars, funs(stem_col(., mtcars[[lag_cols]])))
【问题讨论】:
-
几天前有一个类似的问题:stackoverflow.com/q/53661989/5325862