Reputation: 25
I have a code line which works independently, but I am trying to make it into a function which does not work. Data set:
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")))
Working code:
t.test(cooper$postDist[cooper$group == "Group1"],
cooper$preDist[cooper$group == "Group1"],
alternative = "greater",
paired = TRUE)$p.value
This returns correct value for my chosen group (Group1)
Not-working 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)
Reports "not enough 'x' observations".
Upvotes: 0
Views: 46
Reputation: 886
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)
Upvotes: 1