[R] Data transformation

Steve Lianoglou mailinglist.honeypot at gmail.com
Mon Jan 25 23:55:07 CET 2010


Hi,

On Mon, Jan 25, 2010 at 5:39 PM, Lisa <lisajca at gmail.com> wrote:
>
> Dear all,
>
> I  have a dataset that looks like this:
>
> x <- read.table(textConnection("col1 col2
> 3 1
> 2 2
> 4 7
> 8 6
> 5 10"), header=TRUE)
>
> I want to rewrite it as below:
>
> var1 var2 var3 var4 var5 var6 var7 var8 var9 var10
>    1     0     1      0     0     0     0     0      0      0
>    0     2     0      0     0     0     0     0      0      0
>    0     0     0      1     0     0     1     0      0      0
>    0     0     0      0     0     1     0     1      0      0
>    0     0     0      0     1     0     0     0      0      1
>
> Can anybody please help how to get this done? Your help would be greatly
> appreciated.

I was trying to do it w/o for loops, but I can't figure out a way to do so:

R> bounds <- range(x)
R> m <- matrix(0, nrow=nrow(x), ncol=bounds[2])
R> colnames(m) <- paste('var', seq(bounds[2]), sep="")
## Ugly nested for-loop one-liner below
R> for (i in 1:nrow(x))    for (j in 1:ncol(x)) m[i,x[i,j]] <- m[i,x[i,j]] + 1
R> m

     var1 var2 var3 var4 var5 var6 var7 var8 var9 var10
[1,]    1    0    1    0    0    0    0    0    0     0
[2,]    0    2    0    0    0    0    0    0    0     0
[3,]    0    0    0    1    0    0    1    0    0     0
[4,]    0    0    0    0    0    1    0    1    0     0
[5,]    0    0    0    0    1    0    0    0    0     1

-steve

-- 
Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact



More information about the R-help mailing list