[R] data.frame handling

Tony Plate tplate at acm.org
Tue Mar 20 00:02:34 CET 2007


'table()' can compute your desired result in this particular case 
(though I don't know if it's what you want in general):

 > y <- factor(c("a","b","c")[c(1,1,1,2,2,3,3,3)])
 > x <- factor(c("x","y","z")[c(1,2,3,1,2,1,2,3)])
 > table(x, y)
    y
x   a b c
   x 1 1 1
   y 1 1 1
   z 1 0 1
 >

If x and y are already columns in a data frame, then just do

 > table(X$factor1, X$factor2)

hope this helps,

Tony Plate


Michela Cameletti wrote:
> Dear R-users,
> I have a little problem that I can't solve by myself.
> I have a data frame with 2 factors and 8 observations (see the following
> code):
> 
>  y <- c(1,1,1,2,2,3,3,3)
>  y <- factor(y)
>  levels(y) <- c("a","b","c")
>  x <- c(1,2,3,1,2,1,2,3)
>  x <- factor(x)
>  levels(x) <- c("x","y","z")
>  X  <- data.frame(factor1=x,factor2=y)
> 
> and the final result is
> 
>   factor1 factor2
> 1       x       a
> 2       y       a
> 3       z       a
> 4       x       b
> 5       y       b
> 6       x       c
> 7       y       c
> 8       z       c
> 
>>From the above data I'd like to obtain the following matrix:
> 	a	b	c
> x	1	1	1
> y	1	1	1
> z	1	0	1
> 
> Do you have any advice? Can you help me please?
> Thank you in advance,
> Michela
> 
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list