[R] simple table/matrix problem

William Dunlap wdunlap at tibco.com
Fri Jul 30 18:23:21 CEST 2010



Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Robin Hankin
> Sent: Friday, July 30, 2010 6:40 AM
> To: r-help at r-project.org
> Subject: [R] simple table/matrix problem
> 
> Hi
> 
> Given  three vectors
> 
>   x <- c(fish=3, dogs=5, bats=2)
>   y <- c(dogs=1, hogs=3)
>   z <- c(bats=3, dogs=5)
> 
> How do I create a multi-way table like the following?
> 
>  > out
>       x y z
> bats 2 0 3
> dogs 5 1 5
> fish 3 0 0
> hogs 0 3 0

You could try using a matrix subscript to a matrix
to insert the values, as in:

f <- function (dataList) 
{
    animals <- sort(unique(a <- unlist(lapply(dataList, names),
use.names = FALSE)))
    variables <- names(dataList)
    retval <- array(0, dim = c(length(animals), length(variables)), 
        dimnames = list(animals, variables))
    retval[cbind(match(a, animals), rep(seq_along(dataList), 
                 vapply(dataList, length, integer(1))))] <-
unlist(dataList, use.names = FALSE)
    retval
}
> f(list(x=x,y=y,z=z))
     x y z
bats 2 0 3
dogs 5 1 5
fish 3 0 0
hogs 0 3 0

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> ('out' is a matrix).
> 
> See how the first line shows 'x' has 2 bats, 'y' has zero 
> bats, and 'z' 
> has 3 bats
> and so on for each line.
> The real application would have a matrix of size ~10 by ~10000.
> 
> 
> 
> 
> -- 
> Robin K. S. Hankin
> Uncertainty Analyst
> University of Cambridge
> 19 Silver Street
> Cambridge CB3 9EP
> 01223-764877
> 
> ______________________________________________
> 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