繁体   English   中英

传递data.frame的不同名称以起作用

[英]Passing different names of a data.frame to function

我在这里很基本。 我看了很多例子,但无法找出以下问题。

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

稍微修改您的来电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)
  }

试试吧,它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM