I have a set of vectors V_1, V_2, ..., V_n
that I would like to convert to a matrix. Each vector becomes a column vector in the matrix. The size of each vector is the same. Is there a simple function to do this? In the matrix section of The R Book
it does not appear that this function exists.
What I am currently doing is:
mat=matrix(c(V1, V2, ..., VN), nrow=length(V1))
EDIT: The end goal is to perform a k-means
clustering with this matrix. The names of my vectors are not actually V_1, V_2, ..., V_n
. The names of the vectors are substrings corresponding to the file name which the data come from (this is a 1-1 map). Eventually, I will be iterating over all files in a specific directory, extracting the data into a vector and then appending each column vector to a matrix.
For adding a column to a Matrix in we use cbind() function. To know more about cbind() function simply type ? cbind() or help(cbind) in R.
A matrix can be created in R using the matrix() function. For example, the following code will produce a 3 by 3 matrix: mtx <- matrix(3:11, nrow = 3, ncol = 3) . Moreover, it is possible to combine vectors to create a matrix.
To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.
A command that can work for you is:
sapply(ls(pattern="V[[:digit:]]"),get)
Where the argument in pattern is a regular expression that matches the vectors you want (and only the vectors you want). Alternatively, given that the vectors are named from a substring of some file names, I assume you can create a character vector with each vector name as an element. If so, you can replace the ls command with that vector.
Edit: Matrix append by column would be cbind (column bind). For example:
V1 <- rnorm(20)
V2 <- rnorm(20)
V3 <- rnorm(20)
mat <- matrix(c(V1,V2),nrow=length(V1))
(mat.app <- cbind(mat,V3))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With