我在这里缺少非常基本的东西。我看了很多例子,但无法弄清楚以下问题。
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
答案 0 :(得分:4)
对acast
号召唤的轻微修改可解决问题。
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)
}
试试吧,它有效。