i want to get t-tests between two populations (in or out of treatment group (1 or 0 in sample data below, respectively)) across a number of variables, and for different studies, all of which are sitting in the same dataframe. In the sample data below, I want to generate t-tests for all variables (in sample data: Age, Dollars, DiseaseCnt) between the 1/0 Treatment group. I want to run these t-tests, by Program, rather than across the population. I have the logic to generate the t-tests. However, I need assistance with the final step of extracting the appropriate parts from the function & creating something easily digestable.
Ultimately, what I want is: a table of t-stats, p-values, variable that t-test was performed on, and program for which variable was tested.
DT<-data.frame(
Treated=sample(0:1,1000,replace=T)
,Program=c('Program A','Program B','Program C','Program D')
,Age=as.integer(rnorm(1000,mean=65,sd=15))
,Dollars=as.integer(rpois(1000,lambda=1000))
,DiseaseCnt=as.integer(rnorm(1000,mean=5,sd=2)) )
progs<-unique(DT$Program) # Pull program names
vars<-names(DT)[3:5] # pull variables to run t tests
test<-lapply(progs, function(i)
tt<-lapply(vars, function(j) {t.test( DT[DT$Treated==1 & DT$Program == i,names(DT)==j]
,DT[DT$Treated==0 & DT$Program == i,names(DT)==j]
,alternative = 'two.sided' )
list(j,tt$statistic,tt$p.value) }
) )
# nested lapply produces results in list format that can be binded, but complete output w/ both lapply's is erroneous