将4列矩阵转换为R中的单个1列矩阵

时间:2013-08-29 12:17:33

标签: r matrix

我正在尝试将带有4列的矩阵转换为具有1列的矩阵,如示例所示:

我尝试了代码,但值显示在列表中,我想要值,我可以做一些操作!

f.con <- matrix (c(ex), 
                 ncol=1, byrow=TRUE)

Initial matrix (ex)

0   3   2
0   2   1
0   1   1



Final matrix with 1 colunm:

0
0
0
3
2
1
2
1
1

3 个答案:

答案 0 :(得分:2)

以下是几种可能性:

dim(m) <- c(length(m), 1)
# or
m <- matrix(m, ncol = 1)
然而,后一种方法较慢。

# As I understand, the reason this is fast is that it
# literally transforms the matrix 
m <- matrix(0:1, ncol = 10000, nrow = 10000)
system.time(dim(m) <- c(length(m), 1))
#   user  system elapsed 
#      0       0       0 

m <- matrix(0:1, ncol = 10000, nrow = 10000)
# Whereas here a copy is being made
system.time(m2 <- matrix(m, ncol = 1))
#   user  system elapsed 
#   0.45    0.16    0.61 

# And here a long vector is needed first
system.time(m3 <- as.matrix(c(m)))
Error: cannot allocate vector of size 381.5 Mb

答案 1 :(得分:2)

你能不能只用一个向量而不是一个列矩阵?

as.vector( m )
#[1] 0 0 0 3 2 1 2 1 1

我无法想象R中的操作,使用单列矩阵,但一个相同长度的矢量。

答案 2 :(得分:1)

另一种选择:

> mat <- matrix(c(0,0,0,3,2,1,2,1,1), 3) # your matrix
> as.matrix(c(mat))  # the disired output
      [,1]
 [1,]    0
 [2,]    0
 [3,]    0
 [4,]    3
 [5,]    2
 [6,]    1
 [7,]    2
 [8,]    1
 [9,]    1

请注意,您正在寻找已经在函数c(·)as.vector(·)下在R中实现的vec运算符的实现,如果您真的需要一个向量,它们都会给出一个向量 - 列矩阵,然后只需编写as.matrix(c(·))as.matrix(as.vector(·)),这将适用于任何矩阵大小。

相关问题