[R] What's the BEST way in R to adapt this vector?
Gabor Grothendieck
ggrothendieck at gmail.com
Sun Nov 23 04:12:48 CET 2008
Try this:
outer(y, sort(unique(y)), "==")+0
On Sat, Nov 22, 2008 at 3:37 PM, 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, here's my best:
>
> y <- c(1,2,3,1,2,3,1,2,3,1)
> y.k <- length(unique(y)) #Num. of Categories of y
> y.n <- NROW(y)
> y.nk <- y.n * y.k #Length of new vector
> y.1 <- ifelse(y == 1,1,0)
> y.2 <- ifelse(y == 2,1,0)
> y.3 <- ifelse(y == 3,1,0)
> z <- cbind(y.1, y.2, y.3)
> z.trans <- t(z)
> y.new <- c(1:y.nk); y.new[1:y.nk] <- NA
> y.new <- as.vector(z.trans)
> rm(y.k, y.n, y.nk, y.1, y.2, y.3, z, z.trans)
> y
> y.new
>
> Is there a better a way? I'm still pretty new. Thanks.
> --
> View this message in context: http://www.nabble.com/What%27s-the-BEST-way-in-R-to-adapt-this-vector--tp20638991p20638991.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