简体   繁体   中英

column vectors to matrix in R

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM