0

I'm figuring out how can I solve the issue of passing names in a function, but I'm stuck. This is my code:

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)

The error returne is the following:

Error in eval(expr, envir, enclos) : object 'feature_var' not found

It seems the expression

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

doesn't evaluate the content of the variable feature_var as the column name "giorni_settimanali".

Could you help me?

Thank you

lucazav
  • 858
  • 9
  • 24
  • 1
    Couldn't you simplify this greatly by using ggplot's aes_string() instead of aes()? This would allow you to use character strings directly to refer to columns. – jdobres Apr 01 '17 at 16:46
  • Thank you for your suggestion, @jdobres. I changed all my code passing parameter strings and now it works. I'm just curious about how to pass names in functions called by other functions. Any hint, please? – lucazav Apr 03 '17 at 07:51

0 Answers0