[R] Table to matrix
William Dunlap
wdunlap at tibco.com
Mon May 24 22:30:02 CEST 2010
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Kathryn Lord
> Sent: Monday, May 24, 2010 11:16 AM
> To: r-help at r-project.org
> Subject: [R] Table to matrix
>
> Dear R users,
>
> I am trying to make this (3 by 10) matrix A
>
> --A----------------------------------------------------
>
> 0 0 0 0 1 0 0 0 0 0
> 0 0 0 0 0 1 0 0 0 0
> 0 0.5 0.5 0 0 0 0 0 0 0
>
> -------------------------------------------------------
>
> from "mass.func"
>
> --mass.func-------------------------------------------
> > mass.func
> $`00`
> prop
> 5
> 1
>
> $`10`
> prop
> 6
> 1
>
> $`11`
> prop
> 2 3
> 0.5 0.5
> ---------------------------------------------------------
>
> which means that
>
> A[1,5] = 1
> A[2,6] =1
> A[3,2] = A[3,3] = 0.5
>
> otherwise, zero.
>
> Any suggestion will be greatly appreciated.
>
> Regrads,
>
> Kathryn Lord
>
>
> p.s.
>
> Here is R code.
>
> ------------------------------------------------------------------
>
> > dat <- as.data.frame(matrix( c( 2, 1, 1, 3, 1, 1, 6, 1, 0,
> 5, 0, 0), 4, 3,
> byrow=T))
> > covar <- apply(dat[,-1],1,paste,collapse='')
> > sp.dat <- split(dat,covar)
> > y.covar <- lapply(sp.dat, "[",1)
> >
> > prop <- function(prop) { table(prop)/sum(table(prop)) }
> > mass.func <- lapply(y.covar,prop)
Instead of making many tables and pasting them
together, I would make one table at the start,
as in
> f1 <- function (dat)
{
covar <- paste(dat[, 2], dat[, 3], sep = "")
tbl <- table(covar, factor(dat[, 1], levels = 1:10))
tbl <- sweep(tbl, 1, rowSums(tbl), "/")
tbl
}
> dat <- as.data.frame(matrix(c(2, 1, 1, 3, 1, 1, 6, 1,
0, 5, 0, 0), 4, 3, byrow = T))
> f1(dat)
covar 1 2 3 4 5 6 7 8 9 10
00 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0
10 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0
11 0.0 0.5 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0
Is that the output you are looking for?
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> > mass.func
> $`00`
> prop
> 5
> 1
>
> $`10`
> prop
> 6
> 1
>
> $`11`
> prop
> 2 3
> 0.5 0.5
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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