Skip to content

Instantly share code, notes, and snippets.

/compareGroups.R Secret

Created May 15, 2013 18:42
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/94b79049f1aa3db479e1 to your computer and use it in GitHub Desktop.
A function for comparing a pair of conditions on a variety of variables
compareGroups <- function(dat, Group){
require(reshape2)
#compute group means, SD, and t-tests
tval <- pval <- num <- NA
for (i in 1:ncol(dat)){
num[i] <- is.numeric(dat[,i]) #figure out which columns are numeric
#run t-tests for them
if(is.numeric(dat[,i])){
x <- t.test(dat[,i] ~ dat[,Group], data=dat)
tval[i] <- x$statistic
pval[i] <- format.pval(x$p.value, digits=3, eps=0.0001)
}
}
tt <- data.frame(t=tval[num], p=pval[num])
#get means and SD
M <- aggregate(dat[, num], list(dat[,Group]), mean, na.rm=T)
Mx <- melt(M, id="Group.1")
Mg <- dcast(Mx, variable ~ Group.1)
SD <- aggregate(dat[, num], list(dat[,Group]), sd, na.rm=T)
SDx <- melt(SD, id="Group.1")
g <- merge(Mg, dcast(SDx, variable ~ Group.1), by="variable", sort=F, suffixes = c(".M",".SD"))
##get group sizes
GroupSize <- data.frame("N", t(aggregate(dat[, Group], list(dat[, Group]), length)[,2]), NA, NA)
colnames(GroupSize) <- colnames(g)
#combine for output
GroupCompare <- cbind(rbind(GroupSize, g), rbind(c(NA, NA), tt))
return(GroupCompare)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment