0
x<- c(62, 60, 63, 59, 63, 67, 71, 64, 65, 66, 68, 66, 71, 67, 68, 68, 56, 62, 60, 61, 63, 64, 63, 59)
grp1<- factor(rep(LETTERS[1:2], c(1,2)))
grp2<-rep(1:3)

dat <- data.frame(x,grp1,grp2)

aaa<-function(dset,var,group) {
  if (length(levels(group))==2) {
     ttest<-t.test(dset$var~dat$group)


  }
  else {
     anova<-aov(var~group,data=dset)  


  }
}

How to store t or F value and P value in data frame bbb? I hope that results like: if choose ttest, bbb$stat=t-value,bbb$p<-p-value if choouse anova,bbb$stat=F-value,bbb$p<-p-value Thanks!

stata
  • 513
  • 2
  • 6
  • 12
  • 1
    can you show us what you've tried so far (rather than just giving specifications and asking for code)? You'll need `length(levels(grp1))` and `?"if"`; search Stack Overflow for questions about extracting `t/F/p-values` from output. From a statistical point of view, it's not clear why you would bother, since the results are statistically identical – Ben Bolker May 17 '14 at 15:43

1 Answers1

2

Check out names(ttest) and names(anova), and you'll see how to get t, F and p-values (even better is to check out str instead of names).

> t.test(x~grp1,dat)$statistic
        t 
0.9090048 
> t.test(x~grp1,dat)$p.value
[1] 0.383169

For the ANOVA, I suggest you use the anova function instead:

> anova(lm(x~grp2,dat))[1,"F value"]
[1] 0.2619048
> anova(lm(x~grp2,dat))[1,"Pr(>F)"]
[1] 0.6139134

update: if you just call like this you get an error

aaa(dset=dat,var=x,group=grp1)
Error in model.frame.default(formula = var ~ group, data = dset) : 
  variable lengths differ (found for 'group')

because your variable x has 24 numbers, but grp1 has only 3 (A B C). It is not using your dataframe column names, but your variables. One thing you can do is pass the columns directly to the function:

aaa<-function(var,group) {
  if (length(levels(group))==2) {    
    print("ttest")
  }else{
    print("anova")
  }
}
aaa(dat$x, dat$grp1)
[1] "ttest"
aaa(dat$x, dat$grp2)
[1] "anova"

You can also pass column names appropriately.

Community
  • 1
  • 1
Julián Urbano
  • 8,378
  • 1
  • 30
  • 52