[R] Cross tabulation with fixed dimensions
Gabor Grothendieck
ggrothendieck at gmail.com
Fri Mar 5 17:48:45 CET 2010
Those are numerical, not factors. If they were factors all levels
would be represented.
> a <- factor(c(1,2,3,4,5), levels = 1:5)
> b <- factor(c(1,2,5,5,6), levels = 1:6)
> table(a, b)
b
a 1 2 3 4 5 6
1 1 0 0 0 0 0
2 0 1 0 0 0 0
3 0 0 0 0 1 0
4 0 0 0 0 1 0
5 0 0 0 0 0 1
On Fri, Mar 5, 2010 at 11:43 AM, Tarmo Remmel <remmelt at yorku.ca> wrote:
> 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
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list