繁体   English   中英

R 如何将工作 t.test 命令行转换为 function?

[英]R How to make working t.test command line into function?

我有一个独立工作的代码行,但我试图将它变成一个不起作用的 function。 数据集:

cooper <- data.frame(preDist=c(2454, 2666, 2153, 2144, 2957, 2407, 2167, 2259,
                               1993, 2351, 1642, 2121, 2603, 2669, 2064),
                     postDist=c(2763, 2710, 2272, 2342, 3256, 2617, 2515, 2469,
                                2257, 2637, 1597, 2331, 2616, 2679, 2114),
                     group=factor(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3),
                                  labels=c("Group1", "Group2", "Cont")))

工作代码:

t.test(cooper$postDist[cooper$group == "Group1"], 
       cooper$preDist[cooper$group == "Group1"], 
       alternative = "greater", 
       paired = TRUE)$p.value

这将为我选择的组(Group1)返回正确的值

不工作 function:

pairtest <- function(grp) {
  pvalue <- t.test(cooper$postDist[cooper$group == "grp"], 
                   cooper$preDist[cooper$group == "grp"], 
                   alternative = "greater", paired = TRUE)$p.value
  return(pvalue)
      }
pairtest(Group1)

报告“没有足够的‘x’观察结果”。

pairtest <- function(grp,df) { # add data frame to your input

with(df[df$group == grp,], # filter data frame on input
t.test(preDist,postDist,alternative="greater",paired = T)$p.value)
#changed pre to preDist
#changed post to postDist
}
pairtest("Group1",cooper)

暂无
暂无

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

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