R 如何使工作 t.test 命令行生效?
R How to make working t.test command line into 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) 的这个 returns 正确值
无效函数:
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)
报告 "not enough 'x' observations"。
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)
我有一个独立工作的代码行,但我试图将它变成一个不起作用的函数。 数据集:
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) 的这个 returns 正确值
无效函数:
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)
报告 "not enough 'x' observations"。
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)