[R] Counting two factors at the same time

David Winsemius dwinsemius at comcast.net
Fri Jan 22 20:28:08 CET 2010


On Jan 22, 2010, at 2:07 PM, Fabrice DELENTE wrote:

>> Here's another R-way:
>>
>>> lets<-factor(c( 'A', 'B', 'A', 'C', 'B', 'D', 'B'))
>> # you did say they were factors, right?
>>> nums <- factor(c('1', '2', '2', '3', '2', '2', '3'))
>>> lets=="B"
>> [1] FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE
>>> sum(lets=="B" & nums=="2")
>> [1] 2
>
> Thanks very much, it will save me :^)
>
> As I am a beginner in R, I have a little trouble understanding  
> factors. Can
> they be used interchangeably with lists, or are they a different  
> data-type?
> Can I do on factors everything that I can do on lists?

Not at all. Lists can be arbitrarily complex structures. Factors are  
one-dimensional. The main use of factors is to represent discrete  
groupings of one dimension. Internally elements within factors are  
represented by integers and the levels of the factors are usually  
converted to string-valued "labels" or "'levels". To be frank, I'm not  
clear about how levels and labels could be used in parallel. I  
generally apply functions that work with levels. So factors are much  
more like vectors than they are like lists. To work with R you need to  
have a clear idea of the distinctions between:

lists: tree structures, do have a length property which is the number  
of elements at the top level.
dataframes:  (a specialized type of a two-dimensional list) lengths  
are the number of "columns" rather than the number of rows, can hold  
columns of different types
matrices: 2-dimensional arrays, element are of only one type
arrays:   n-dimensional
vectors 1-dim, elements all of the same type: logical, integer,  
numeric or character
factors 1-dim, essentially integers with character labels

>
> Thanks again!
>
> -- 
> Fabrice DELENTE
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list