[R] Function for multiple t tests

Iuri Gavronski iuri at ufrgs.br
Sun Jan 22 02:57:46 CET 2012


I didn't find any function for that and found easier write one. It is
not the most elegant solution, but in case anyone wants it:

ttable <- function(formula, data, digits=2) {
  vars = all.vars(formula)
  nvars = length(vars)
  nnumvars = nvars - 1
  factorname = vars[nvars]
  outp = matrix(ncol=6,nrow=nvars+1)
  for(vari in 1:nnumvars) {
    outp[vari,c(2,4)]=by(data[,vars[vari]],data[factorname],sd)
    tt = t.test(as.formula(paste(vars[vari],factorname,sep=" ~ ")),data)
    outp[vari,5]=tt$statistic
    outp[vari,6]=tt$p.value
    outp[vari,c(1,3)]=tt$estimate
  }
  outp=round(outp,digits)
  outp[nvars,c(1,3)] = levels(as.factor(data[,factorname]))
  outp[nvars+1,c(1,3)]=by(data[,vars[vari]],data[factorname],length)
  colnames(outp) = c("Mean","s.d.","Mean","s.d.","t-test","p-value")
  rownames(outp) = c(vars,"N")
  outp
}

my_swiss = swiss[-1,]
my_swiss$facto = rep(1:2,nrow(my_swiss)/2)
ttable(Fertility + Agriculture ~ facto, data=my_swiss)

On Sat, Jan 21, 2012 at 7:40 PM, Iuri Gavronski <iuri at ufrgs.br> wrote:
> Hi,
>
> I want to run t.test() for several variables among two groups, and I
> would like to skip the tedious process of collecting information to
> assemble a table, but I am not sure if the function I want already
> exists. Any suggestion would be appreciated.
>
> I have a working example, as required by the posting guide:
>
> my_swiss = swiss[-1,]
> my_swiss$facto = rep(1:2,nrow(my_swiss)/2)
> t.test(Fertility~facto,data=my_swiss)
> by(my_swiss$Fertility,my_swiss$facto, sd)
> t.test(Agriculture~facto,data=my_swiss)
> by(my_swiss$Agriculture,my_swiss$facto, sd)
>
>
> ttable <- function(formula, data) { ???? }
>
> ttable(Fertility + Agriculture ~ facto, data=my_swiss)
>
> facto              1                          2
>              Mean  s.d.                  Mean s.d.  t-test p-value
> Fertility      69.19 10.66               70.66 14.38 -0.39  0.70
> Agriculture    51.65 21.15               51.13 24.05 0.08 0.94



More information about the R-help mailing list