r - 在调用 ezANOVA : How do I parameterize the dv? 的自定义 R 函数中

标签 r

我正在尝试在函数中使用 ez 包中的 ezANOVA,在该函数中我希望允许使用参数指定 dv。通常,ezANOVA 会接受列变量作为符号或字符串(请参阅下面的“此方法”)。但是,尝试为 ezANOVA 提供包含符号或字符的参数是行不通的(请参阅下面的“这行不通”)。 ezANOVA 提示““the_dv”不是提供的数据框中的变量”。我尝试过用 as.symbol()、as.formula() 等各种方法包装变量名,甚至尝试了各种方法来合并 eval() 和 Replacement(),但都没有成功。这是如何实现的?

如果它的原因有帮助,我有一个项目,我需要进行许多复合分析(均值、方差分析、事后分析、图表),这些分析与所分析的数据集或变量相同。我想要一个函数,这样我就可以编写一次并运行它多次。下面的代码只是一个简单的示例。

library(ez)

df<-data.frame(ID=as.factor(101:120), 
               Training=rep(c("Jedi", "Sith"), 10), 
               Wins=sample(1:50, 20), 
               Losses=sample(1:50, 20))

# ----------
# This Works
# ----------

myfunc1 <- function(the_data) {
  ezANOVA(
    data = the_data,
    wid = ID,
    dv = Wins,
    between = Training
  )
}

myfunc1(the_data = df)

# ------------------
# This Does Not Work
# -------------------

myfunc2 <- function(the_data, the_dv) {
  ezANOVA(
    data = the_data,
    wid = ID,
    dv = the_dv,
    between = Training
  )
}

myfunc2(the_data = df, the_dv = Wins)  # 'Wins' also fails

最佳答案

必须自己解决这个问题。事实证明,eval() 和 Replace() 的组合解决了这个难题:

# ----------------------------------
# Aha, it works!
# ----------------------------------

library(ez)

df<-data.frame(ID=as.factor(101:120), 
               Training=rep(c("Jedi", "Sith"), 10), 
               Wins=sample(1:50, 20), 
               Losses=sample(1:50, 20))

myfunc2 <- function(the_data, the_dv) {
  eval(
    substitute(
      ezANOVA(data = the_data, 
              wid = ID, 
              dv = the_dv, 
              between = Training), 
      list(the_dv = the_dv)))
}

myfunc2(the_data = df, the_dv = 'Wins')
myfunc2(the_data = df, the_dv = 'Losses')

享受吧!!

关于r - 在调用 ezANOVA : How do I parameterize the dv? 的自定义 R 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616639/

相关文章:

R - 总结相对学期序列的类(class)注册

python - SQL "partition by"Python/R 中的类似功能

r - 时间序列及其可视化

string - R - paste() 在将数据帧传递给它时调用 as.numeric() 吗?

performance - cor() 函数是如何加速的?

r - 在 RStudio 的 R 包中记录 R6 类和方法

r - 在 Shiny 中格式化sliderInput的数字输出

r - 使用 scale_x_discrete 和 scale_x_continuous 自定义 x 轴刻度

r - 将 "25\%"粘贴到 R 中,以便在 LaTeX 中进一步处理

r - 如何使用ggplotGrob和annotation_custom将grob与ggplot对齐?