Skip to content
Prev 277998 / 398506 Next

Need help with table() and apply()

The answer to your question as to why you had to convert back to
factors is that you "undid" the factors when you did the 'cbind' to
create the dataframe.  Here is what you should have done:
+                          rating.5 , rating.6 , rating.7 , rating.8 ,
+                          rating.9 , rating.10)
'data.frame':   10 obs. of  10 variables:
 $ rating.1 : Factor w/ 4 levels "1","2","3","4": 4 1 2 4 3 2 4 1 2 1
 $ rating.2 : Factor w/ 4 levels "1","2","3","4": 2 3 2 3 2 2 1 3 3 3
 $ rating.3 : Factor w/ 4 levels "1","2","3","4": 3 1 1 3 2 1 3 3 1 3
 $ rating.4 : Factor w/ 4 levels "1","2","3","4": 4 2 2 2 2 4 3 3 3 4
 $ rating.5 : Factor w/ 4 levels "1","2","3","4": 1 2 2 2 1 2 3 3 4 4
 $ rating.6 : Factor w/ 4 levels "1","2","3","4": 3 2 2 1 2 2 3 3 3 2
 $ rating.7 : Factor w/ 4 levels "1","2","3","4": 3 4 2 2 4 3 4 4 4 4
 $ rating.8 : Factor w/ 4 levels "1","2","3","4": 4 1 3 1 3 1 4 4 3 3
 $ rating.9 : Factor w/ 4 levels "1","2","3","4": 4 4 2 3 2 4 3 2 3 2
 $ rating.10: Factor w/ 4 levels "1","2","3","4": 1 2 1 3 2 2 3 1 1 1

Notice that the factors are maintained.

When having problems, break up the steps and see what happens at each
one.  Here is the output of your 'cbind':
+                          rating.5 , rating.6 , rating.7 , rating.8 ,
+                          rating.9 , rating.10)
+ )
int [1:10, 1:10] 4 1 2 4 3 2 4 1 2 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:10] "rating.1" "rating.2" "rating.3" "rating.4" ...
notice it is just an integer array.

Also if you had looked at the HELP page, you would have seen:

In the default method, all the vectors/matrices must be atomic (see
vector) or lists. Expressions are not allowed. Language objects (such
as formulae and calls) and pairlists will be coerced to lists: other
objects (such as names and external pointers) will be included as
elements in a list result. Any classes the inputs might have are
discarded (in particular, factors are replaced by their internal
codes).

Notice the last sentence.

2011/11/20 Stuart Luppescu <slu at ccsr.uchicago.edu>: