[R] Loop for CrossTable (gmodels)

arun smartpink111 at yahoo.com
Sun May 12 19:30:25 CEST 2013

According to the error, the variables should have the same length.
For example:
dat1<- cbind(RACE=sample(1:10,10,replace=TRUE),as.data.frame(matrix(sample(1:100,20*10,replace=TRUE),ncol=20)))
 lapply(dat1[,-1],function(x) CrossTable(x,dat1$RACE,format="SPSS",prop.chisq=FALSE,digits=2,dnn=c("VAR","RACE"))) # prints cross tables.

 lapply(names(dat1)[-1],function(x) CrossTable(dat1[,x],dat1[,"RACE"],format="SPSS",prop.chisq=FALSE,digits=2,dnn=c(x,"RACE")))
>I have 20 variables in a data frame (VAR1 ... VAR20) which I would like to crosstab against the variable RACE. 
>I would like to use a loop structure instead of 20 statements like: 
>CrossTable(VAR1, RACE, format = "SPSS", prop.chisq = FALSE, digits = 2) 
>I have tried following syntax, but failed: 
>for(i in 1:20){ 
>columnname <- ("VAR",i) 
>CrossTable(columnname, RACE, format = "SPSS", prop.chisq = FALSE, digits = 2) 
>I receive following Error: 
>Error in CrossTable(columnname, RACE, format = "SPSS", prop.chisq = FALSE,  : 
 > x and y must have the same length 
>Any idea how to get 20 crosstables within a loop? 
>Thank you for any hints, 

More information about the R-help mailing list