Reputation: 23898
I'm missing very basic here. I looked many examples but could not figure out the following problem.
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
Upvotes: 1
Views: 36
Reputation: 76470
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.
Upvotes: 4