[R] Data transformation
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Jan 26 00:09:02 CET 2010
Try this:
> t(apply(x, 1, function(r) table(factor(r, levels = seq_len(max(x))))))
1 2 3 4 5 6 7 8 9 10
[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
If you use aaply in the plyr package instead of apply then you can
omit the transpose.
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.
>
> Lisa
>
> --
> View this message in context: http://n4.nabble.com/Data-transformation-tp1289899p1289899.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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