[R] Need a factor level even though there are no observations

Ajay Narottam Shah ajayshah at mayin.org
Sun May 8 15:56:55 CEST 2005


I'm in this situation:

     factorlabels <- c("School", "College", "Beyond")

with data for 8 families:

     education.man  <- c(1,2,1,2,1,2,1,2)       # Note : no "3" values
     education.wife <- c(1,2,3,1,2,3,1,2)       # 1,2,3 are all present.

My goal is to create this table:

                     School     College      Beyond
       Husband       4          4            0
       Wife          3          3            2


How do I do this?

I can readily do:
     education.wife <- factor(education.wife, labels=factorlabels)

But this breaks:
     education.man <- factor(education.man,   labels=factorlabels)

because none of the families have a husband who went beyond college.

I get around this problem in a limited way by:
     cautiously <- function(x, labels) {
       factor(x, labels=factorlabels[as.numeric(levels(factor(x)))])
     }
     education.man <- cautiously(education.man, labels=factorlabels)

Now I get:

     > table(education.man)
     School College 
          4       4 
     > table(education.wife)
     School College  Beyond 
          3       3       2 

This is a pain because now the two tables are not conformable. How do
I get to my end goal, which is the table:

                     School     College      Beyond
       Husband       4          4            0
       Wife          3          3            2

In other words, how do I force education.man to have a factor with 3
levels - "School" "College" "Beyond" - even though there is no
observation in "Beyond".

-- 
Ajay Shah                                                   Consultant
ajayshah at mayin.org                      Department of Economic Affairs
http://www.mayin.org/ajayshah           Ministry of Finance, New Delhi




More information about the R-help mailing list