[R] Need a factor level even though there are no observations
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sun May 8 19:32:19 CEST 2005
Set levels not labels in the factor call. E.g.
> factor("School", levels = factorlabels)
On Sun, 8 May 2005, Ajay Narottam Shah wrote:
> 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list