$ operator invalid for atomic vectors

I have a very simple dataset and I tried to execute table () on the first column of the table, but R returns an error header message. I searched on the Internet, but I don’t quite understand why this will happen, since R takes my table as a table ... can anyone advise?

My expected result:

> table(tab$V1) CA 1 CO 1 OH 2 

However, it returns:

 > tabraw V1 V2 1 OH Cleveland 2 OH Columbus 3 CO Denver 4 CA SanFran > tab <- table(tabraw) > tab V2 V1 Cleveland Columbus Denver SanFran CA 0 0 0 1 CO 0 0 1 0 OH 1 1 0 0 > table(tab$V1) Error in tab$V1 : $ operator is invalid for atomic vectors 
+7
r
source share
2 answers

You are looking for

 table(tabraw$V1) # # CA CO OH # 1 1 2 

The tab object is a class table object and does not support the $ function.

You can also get the information you need from the tab object using

 rowSums(tab) # CA CO OH # 1 1 2 
+6
source share

You should think of table objects as matrices from which 2D inherit all of its indexing properties (so [ dim-indices ] ):

 is.matrix(tab) # returns TRUE 

If you have a table with more than 2d, it naturally inherits its access functions from the array class. The only (typical) data class that uses $ as access is a list (from which datasets are inherited). Try:

 tab[ , 1] # Or tab[ , "Cleveland"] 

(I suppose I shouldn't have been so categorical about β€œ$.” You can access elements of some language objects and environment objects with this accessory, because they behave like lists.)

+3
source share

All Articles