[R] Need help with table() and apply()

Stuart Luppescu slu at ccsr.uchicago.edu
Sun Nov 20 22:56:51 CET 2011


Hello, I am having trouble getting counts of values in rows of a data
frame. I'm trying to use apply, but it's not working.

This gives a sample of the kind of data I'm working with:

rating.1 <- factor(sample(1:4, size=10, replace=T), levels=1:4)
rating.2 <- factor(sample(1:4, size=10, replace=T), levels=1:4)
rating.3 <- factor(sample(1:3, size=10, replace=T), levels=1:4)
rating.4 <- factor(sample(2:4, size=10, replace=T), levels=1:4)
rating.5 <- factor(sample(1:4, size=10, replace=T), levels=1:4)
rating.6 <- factor(sample(1:3, size=10, replace=T), levels=1:4)
rating.7 <- factor(sample(2:4, size=10, replace=T), levels=1:4)
rating.8 <- factor(sample(1:4, size=10, replace=T), levels=1:4)
rating.9 <- factor(sample(2:4, size=10, replace=T), levels=1:4)
rating.10 <- factor(sample(1:3, size=10, replace=T), levels=1:4)

df <- as.data.frame(cbind(rating.1 , rating.2 , rating.3 , rating.4 ,
                          rating.5 , rating.6 , rating.7 , rating.8 ,
                          rating.9 , rating.10))

for(i in 1:10) {
  df[,i] <- factor(df[,i], levels=1:4)
}

[Aside: why does the original df have columns of class "integer" when
the original data are factors? Why is it necessary to reconvert them
into factors? Also, is it possible to do this without a for loop?]

If I do this:

apply(df[,1:10], 1, table)

I get a 4x10 array, the contents of which I do not understand.

apply(df[,1:10], 2, table)

gives 10 tables for the columns, but it leaves out factor levels which
do not occur. For example,

 rating.6 : 'table' int [1:3(1d)] 7 1 2
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr [1:3] "1" "2" "3"

lapply(df[, 1:10], table)

gives tables of the columns keeping the levels with 0 counts:

$ rating.6 : 'table' int [1:4(1d)] 7 1 2 0
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr [1:4] "1" "2" "3" "4"

But I really want tables of the rows. Do I have to write my own function
to count the numbers of values?

Thanks in advance.

-- 
Stuart Luppescu -=- slu .at. ccsr.uchicago.edu 
University of Chicago -=- CCSR 
才文と智奈美の父  -=- Kernel 3.0.6-gentoo
 You say yourself it wasn't reproducible. So it could have been anything
that "crashed" your R, cosmic radiation, a bolt of lightning reversing a
bit in your computer memory, ... :-) -- Martin Maechler (replying to a
bug report) R-devel (July 2005)



More information about the R-help mailing list