2017-09-23 17 views
1

ここでは基本的に欠けています。私は多くの例を見たが、次の問題を理解することはできなかった。関数へのdata.frameの異なる名前の受け渡し

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 

答えて

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) 
    } 

試してみてください。

+0

すてきな答えのための@Ruiありがとうございます。 – MYaseen208

関連する問題