[R] vectors into a matrix
varenda44 at gmail.com
varenda44 at gmail.com
Thu Jan 7 15:03:15 CET 2010
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
More information about the R-help
mailing list