[R] Cross tabulation with fixed dimensions

Tarmo Remmel remmelt at yorku.ca
Fri Mar 5 17:43:59 CET 2010


Hello,

This is a seemingly simple task, but it has been frustrating me for too
long, so I am turning to this list for some help.

I have two vectors of factors which are quite long; two simple examples are
shown here:

> a <- c(1,2,3,4,5)
> b <- c(1,2,5,5,6)

If I produce a cross-tabulation of these vectors, I get the following:

> tab <- table(a,b)

> table(a,b)
   b
a   1 2 5 6
  1 1 0 0 0
  2 0 1 0 0
  3 0 0 1 0
  4 0 0 1 0
  5 0 0 0 1

I really want to have this cross-tabulation expanded to include all factors
present in the input data.  Thus, I need additional columns for categories 3
and 4, and a row for category 6, albeit, they will be filled with zeros.  Is
there an easy way of doing this?

Thanks,

Tarmo



____________________________________________
Tarmo K. Remmel Ph.D.
Assistant Professor, Department of Geography
York University, N413A Ross Building
Toronto, Ontario, M3J 1P3, Canada
Tel: 416-736-2100 x22496; Fax: 416-736-5988
http://www.yorku.ca/remmelt
Skype: tarmoremmel



More information about the R-help mailing list