MYaseen208 MYaseen208 - 23 days ago 8
R Question

Passing different names of a data.frame to function

I'm missing very basic here. I looked many examples but could not figure out the following problem. Any help will be highly appreciated. Thanks

df1 <- data.frame(
Rep = factor(rep(1:3, each = 4, times = 2)),
Gen = rep(paste0("T", 1:4), times = 6),
Env = rep(paste0("Loc", 1:2), each = 12),
Y = rnorm(24)
)

GEMeans <-
function(data, G, E, Y){
G <- deparse(substitute(G))
E <- deparse(substitute(E))
Y <- deparse(substitute(Y))

Means <-
reshape2::acast(
data = data
, formula = data[[G]] ~ data[[E]]
, fun.aggregate = mean
, margins = TRUE
, value.var = data[[Y]]
)
return(Means)
}


GEMeans(df1, Gen, Env, Y)

Error in `[.data.frame`(df, vars) : undefined columns selected

Answer Source

Slight modifications to your call to acast solve the problem.

GEMeans <- 
  function(data, G, E, Y){
    G   <- deparse(substitute(G))
    E   <- deparse(substitute(E))
    Y <- deparse(substitute(Y))
    Means <- 
    reshape2::acast(
        data          = data
      , formula       = as.formula(paste(G, E, sep = "~"))  # here
      , fun.aggregate = mean
      , margins       = TRUE
      , value.var     = Y    # and here
    )
    return(Means)
  }

Try it, it works.