[R] What's the BEST way in R to adapt this vector?

Berwin A Turlach berwin at maths.uwa.edu.au
Sun Nov 23 04:17:03 CET 2008


On Sat, 22 Nov 2008 10:00:18 -0800 (PST)
zerfetzen <zerfetzen at yahoo.com> wrote:

> Goal:
> Suppose you have a vector that is a discrete variable with values
> ranging from 1 to 3, and length of 10.  We'll use this as the example:
> 
> y <- c(1,2,3,1,2,3,1,2,3,1)
> 
> ...and suppose you want your new vector (y.new) to be equal in length
> to the possible discrete values (3) times the length (10), and
> formatted in such a way that if y[1] == 1, then y.new[1:3] ==
> c(1,0,0), and if y[2] == 2, then y.new[4:6] == c(0,1,0).  For
> example, the final goal should be:
> 
> y.new <-
> c(1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0)
> 
> Note: I know how to do this with loops, but that's not taking
> advantage of R's capabilities with vectors and, I suspect, matrices.

> So far, my best guess would be to start as follows:
[....]

My guess would be to use:

R> y <- c(1,2,3,1,2,3,1,2,3,1)
R> y.new <- as.numeric(as.vector(outer(sort(unique(y)), y, "==")))
R> y.new
 [1] 1 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0


> [...] From here, maybe put these into a 10x3 matrix, and read them out
> by row into y.new?  

Better put them into a 3x10 matrix and then turn the matrix into a
vector by as.vector().  Essentially, a matrix is a vector with an
attribute giving the dimensions of a matrix and as.vector() removes that
attribute.  Furthermore, in R (just as in Fortran), matrices are stored
in column major format; thus, as soon as the dim attribute is removed,
the values are in the correct order.

HTH.

Cheers,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6516 4416 (secr)
Dept of Statistics and Applied Probability        +65 6516 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore     
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list