Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

column vectors to matrix in R

Tags:

r

matrix

k-means

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))
  1. Is there some kind of matrix append function to append columns onto the end of a matrix?

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.

like image 788
CodeKingPlusPlus Avatar asked Feb 15 '13 04:02

CodeKingPlusPlus


People also ask

How do I add a column vector to a matrix in R?

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.

How do you make a column into a matrix 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.

How do I convert a vector to a matrix in R?

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.


1 Answers

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))
like image 142
russellpierce Avatar answered Oct 06 '22 21:10

russellpierce