我有一个长度为 R*N 的单列数据,我想将它转换成 R 行 N 列的矩阵。有没有简单的方法可以实现这个目标而不使用循环和逐个赋值?
格式如下:
r1
r2
r3
..
rR*N
将其转换为
r(1..N)
r(N+1 .. 2*N)
...
在R中这很简单。假设你的对象叫做dat
:
matrix(dat, R, byrow=TRUE)
此处的R
表示行数。
如果您的数据集很大,您可能希望节省内存。以下是一个简单的示例:
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
> class(x)
[1] "matrix"
byrow=TRUE
。 - James