How to convert a single column to a matrix in R

2019-05-28 16:17发布

问题:

I have a single column in length of R*N, I want to convert it a RxN matrix in R. Is there any simple way to accomplish this without using loops and value by value assignments ?

Format is

r1
r2
r3

..

rR*N

convert it to

r(1..N)
r(N+1 .. 2*N)
...

回答1:

This is very simple in R. Assuming your object is called dat:

matrix(dat, R, byrow=TRUE)

where R denotes the number of rows.



回答2:

You may want to conserve memory if your data set is large. Here is a simple example:

x = round(runif(15, min=1, max=15));
## use dim() to set dimensions instead of matrix() to avoid duplication of x
dim(x) <- c(3, 5);
rowNames = c("row1", "row2", "row3");
colNames = c("c1", "c2", "c3", "c4", "c5");
dimnames(x) = list(rowNames, colNames);
print(x);



     c1 c2 c3 c4 c5
row1  7  2  2 11  9
row2  2  6 11 14 10
row3  2 11  6 13 12

Note that the class of "x" is now "matrix":

> class(x)
[1] "matrix"


标签: r vector matrix