[R] vectors into a matrix

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Thu Jan 7 15:11:22 CET 2010


you could try something like this:

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)

n <- 4
do.call(rbind, lapply(paste("VD", 1:n, sep = ""), get))


I hope it helps.

Best,
Dimitris


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
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list