2010-09-29 241 views

回答

157

可以用'scan'读入它,或者只是在矩阵上做as.vector()。如果需要按行或列,您可能需要先转置矩阵。该解决方案发布至今都是很恶心我还没有想尝试...

> m=matrix(1:12,3,4) 
> m 
    [,1] [,2] [,3] [,4] 
[1,] 1 4 7 10 
[2,] 2 5 8 11 
[3,] 3 6 9 12 
> as.vector(m) 
[1] 1 2 3 4 5 6 7 8 9 10 11 12 
> as.vector(t(m)) 
[1] 1 4 7 10 2 5 8 11 3 6 9 12 
+4

这应该是被接受的解决方案,因为问题标题清楚地表明矩阵输入 – C8H10N4O2 2016-03-25 13:07:13

+0

转置矩阵是天才! – LostLin 2017-12-21 20:49:35

9

?matrix:“矩阵是二维'数组'的特例。”你可以简单地改变矩阵/数组的尺寸。

Elts_int <- as.matrix(tmp_int) # read.table returns a data.frame as Brandon noted 
dim(Elts_int) <- (maxrow_int*maxcol_int,1) 
+1

阅读表返回一个data.frame不是矩阵。如果没有as.matrix(),这仍然可以工作吗? – 2010-09-29 16:16:18

+0

@Brandon不会的;接得好! – 2010-09-29 16:21:37

1

您可以使用约书亚的解决方案,但我认为你需要Elts_int <- as.matrix(tmp_int)

或者for循环:

z <- 1 ## Initialize 
counter <- 1 ## Initialize 
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32 
for (x in 1:32) { 
z[counter] <- tmp_int[x,y] 
counter <- 1 + counter 
} 
} 

z是一维向量。

27

如果我们谈论data.frame,那么你应该问自己是同一类型的变量?如果是这样的话,你可以rapply,或选择不公开使用,因为data.frames的名单,在他们的灵魂深处......

data(mtcars) 
unlist(mtcars) 
rapply(mtcars, c) # completely stupid and pointless, and slower 
+0

'unlist'为我工作。 – 2017-03-05 08:05:08

23

尝试c()

x = matrix(1:9, ncol = 3) 

x 
    [,1] [,2] [,3] 
[1,] 1 4 7 
[2,] 2 5 8 
[3,] 3 6 9 

c(x) 

[1] 1 2 3 4 5 6 7 8 9 
+0

这是一个向量,而不是一维数组。 – hadley 2010-09-29 20:35:25

+0

嗯。确实如此。也许不是一维数组,而是一维矢量。 – Greg 2010-09-29 21:59:37

10

array(A)array(t(A))会给你一个一维数组。

1

简单和快速,因为一维数组本质上是一个矢量

vector <- array[1:length(array)] 
5

它可能是这么晚了,反正这是我在矩阵转换为矢量方式:

library(gdata) 
vector_data<- unmatrix(yourdata,byrow=T)) 

希望这将有助于

1

如果你有一个data.frame(df)有多个列,并且你想要矢量化,你可以做

as.matrix(df,ncol = 1)

+0

这也适用于矩阵。 – 2017-01-25 15:11:28

1

您可以使用as.vector()。它看起来是根据我的小基准最快方法,如下所示:

library(microbenchmark) 
x=matrix(runif(1e4),100,100) # generate a 100x100 matrix 
microbenchmark(y<-as.vector(x),y<-x[1:length(x)],y<-array(x),y<-c(x),times=1e4) 

第一解决方案使用as.vector(),第二个使用的是一个矩阵被存储在存储器中的连续的阵列和length(m)给出了这样的事实矩阵中元素的数量m。第三个从x实例化array,第四个使用连接函数c()。我也尝试unmatrixgdata,但它太慢,不能在这里提到。

这里有一些我所获得的数值结果:

> microbenchmark(
     y<-as.vector(x), 
     y<-x[1:length(x)], 
     y<-array(x), 
     y<-c(x), 
     times=1e4) 

Unit: microseconds 
       expr min  lq  mean median  uq  max neval 
    y <- as.vector(x) 8.251 13.1640 29.02656 14.4865 15.7900 69933.707 10000 
y <- x[1:length(x)] 59.709 70.8865 97.45981 73.5775 77.0910 75042.933 10000 
     y <- array(x) 9.940 15.8895 26.24500 17.2330 18.4705 2106.090 10000 
      y <- c(x) 22.406 33.8815 47.74805 40.7300 45.5955 1622.115 10000 

平展矩阵在机器学习,共同操作,其中一个矩阵可以代表参数来学习,但一个从一个普通的采用优化算法库期望一个参数向量。所以通常将矩阵(或矩阵)转换成这样的向量。标准R功能optim()就是这种情况。