From: <Jagat.K.Sheth_at_wellsfargo.com>

Date: Sun, 23 Nov 2008 20:00:00 -0600

Date: Sun, 23 Nov 2008 20:00:00 -0600

bEST is up to you to define. Here is one simple way

y.new <- c(t(model.matrix(~factor(y)-1)))

-----Original Message-----

From: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org]
On Behalf Of zerfetzen

Sent: Saturday, November 22, 2008 12:00 PM
To: r-help_at_r-project.org

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

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:

y1 <- ifelse(y == 1, 1, 0) y2 <- ifelse(y == 2, 1, 0) y3 <- ifelse(y == 3, 1, 0)

>From here, maybe put these into a 10x3 matrix, and read them out by row

*>into
*

y.new? Is that even the most efficient way? If it is, I'm sure I can
get them into a matrix, but how do I read them out correctly? Thanks
for any input.

-- View this message in context: http://www.nabble.com/What%27s-the-BEST-way-in-R-to-adapt-this-vector--t p20638991p20638991.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. ______________________________________________ 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.Received on Mon 24 Nov 2008 - 02:03:45 GMT

Archive maintained by Robert King, hosted by
the discipline of
statistics at the
University of Newcastle,
Australia.

Archive generated by hypermail 2.2.0, at Mon 24 Nov 2008 - 02:30:29 GMT.

*
Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help.
Please read the posting
guide before posting to the list.
*