在另一个函数内的函数中传递数据框列名

时间:2017-04-01 16:41:18

标签: r

我想知道如何解决函数中传递名称的问题,但我陷入了困境。 这是我的代码:

plotScatter <- function(data_in, var_x, var_y, title) {
    xx <- eval(substitute(var_x), eval(data_in))
    yy <- eval(substitute(var_y), eval(data_in))

    data <- data.frame(x = xx, y = yy)
    p <- ggplot(data, aes(x = x, y = y)) +
         geom_point(shape = 1, na.rm = TRUE) +
         geom_smooth(method = lm) +
         ggtitle(title) +
         xlab(paste0(substitute(var_x), '\n', 'R-Squared: ', round(cor(data$x, data$y, use = 'complete.obs'), 2))) +
         ylab(substitute(var_y)) +
         theme_light()
    return(suppressWarnings(p))
}

doPlots <- function(data_in, fun, filter_var, filter_vector, feature_var, target_var) {
    ncol <- length(filter_vector) %/% 2
    pp <- list()

    for (v in filter_vector) {
        filtered_data <- subset(data_in, substitute(filter_var) == v)

        p <- fun(data_in = filtered_data, var_x = feature_var, var_y = target_var, title = v)
        pp <- c(pp, list(p))
    }
    do.call("grid.arrange", c(pp, ncol = ncol))
}


doPlots(data_in = df, fun = plotScatter, filter_var = codice_apparato,
    filter_vector = apparati, feature_var = giorno_settimana, target_var = num_transiti_in)

错误返回如下:

  

eval(expr,envir,enclos)中的错误:object&#39; feature_var&#39;找不到

似乎是表达式

p <- fun(data_in = filtered_data, var_x = feature_var, var_y = target_var, title = v)

不会将变量feature_var的内容评估为列名&#34; giorni_settimanali&#34;。

你能帮帮我吗?

谢谢

0 个答案:

没有答案