[R] vectors into a matrix

Marc Schwartz marc_schwartz at me.com
Thu Jan 7 15:19:40 CET 2010


On Jan 7, 2010, at 8:03 AM, varenda44 at gmail.com wrote:

> Hello all,
>
>
> Firstly, thanks a lot for all your efforts,
> the cbind function was very useful.
>
> I tried all you told me, but I couldn't make it work in the way I  
> wanted.
> I mixed two problems I had, a common mistake.
> Sorry if I didn't explain myself good enough.
>
> Here, I post a solution for my problem.
> I wanted to avoid the "while" loop but I've finally used it.
> Hopefully it is helpfull for someone else.
>
>
> CODE:
> -------------------------------
>
>
> # This could be my data:
>
> VD1 <- c(12, 34, 45, 7, 67, 45)
> VD2 <- c(23, 12, 45, 67, 89, 90)
> VD3 <- c(14, 11, 10, 19, 20, 27)
> VD4 <- c(16, 22, 23, 29, 27, 28)
>
>
> # and this is my objective:
> # (in this case it is just for 4 vectors)
>
> AIM <- matrix(c(VD1, VD2, VD3, VD4), nrow=4, byrow=TRUE)
> print(AIM)
>
> # but I want to use any number of vectors
> # VDx when x goes from 1 to n
>
> n <- 4  # for this case.
>
> # A solution:
> # build an empty matrix with the desired number of rows (vectors)
> # then with a "while" loop fill each row with each vector.
>
> Final.matrix <- matrix(, nrow=n, ncol=6, byrow=TRUE)
> print(Final.matrix)
>
> y <- 1
> while (y <= n)
> {
>  c <- eval(parse(text=(paste("VD", sep="", y))))
>  Final.matrix[y,] <- c
>  y <- y + 1
> }
>
> print(Final.matrix)
>
> # If I set "n" as 12 I will get the example I explained at first
> # then, by using "cbind()" and "1:n" I add the values of the first  
> column
> # as many of you suggested to me
>
> ---------------------------------------
>
> If someone comes up with a way to do this avoiding the loop, I'd be  
> very
> interested to get to know the solution.
>
>
> Kind regards,
>
> Vilen
>
> Forestry Engineer


library(fortunes)

 > fortune("parse")

If the answer is parse() you should usually rethink the question.
    -- Thomas Lumley
       R-help (February 2005)



An easier way is to use get() along with ls(), using a regex pattern  
in the latter. That will get you the objects which you can then  
manipulate as desired.


# see ?regex
 > ls(pattern = "^VD[0-9]+$")
[1] "VD1" "VD2" "VD3" "VD4"


# This presumes that each vector is the same length, such that using  
sapply() will return a matrix rather than a list.
 > t(sapply(ls(pattern = "^VD[0-9]+$"), get))
     [,1] [,2] [,3] [,4] [,5] [,6]
VD1   12   34   45    7   67   45
VD2   23   12   45   67   89   90
VD3   14   11   10   19   20   27
VD4   16   22   23   29   27   28

HTH,

Marc Schwartz



More information about the R-help mailing list