Skip to content
Prev 323404 / 398503 Next

Loop for CrossTable (gmodels)

On May 12, 2013, at 10:30 AM, arun wrote:

            
It might be productive in learning R to understand what you were doing wrong and how you could have used that control for-loop structure. It does appear that you have `attach`-ed a data.frame and are referring to the column names. Yes? If so, you should realize that is not a particularly safe practice, but let's push on.

columnname is just  a character vector with a single element, "VAR1" the first time around. R does not do a double-evaluation to first figure out that `columnname` is "VAR1" and then proceed further to look up its value. To do that you would need to add `get`:

for(i in 1:20){ 
   columnname <- ("VAR",i) 
   CrossTable( get(columnname), RACE, format = "SPSS", prop.chisq = FALSE, digits = 2) 
} 

The get function does the extra step of converting the character value to an object name and returning the value of that named data-object.
That should do it. It would have been better if you had used dput() to produce a workable small example of a few of the columns.

David Winsemius
Alameda, CA, USA