将matrix转换为1维数组

我有一个matrix(32X48)。

如何将matrix转换为单维数组?

如果我们正在谈论data.frame,那么你应该问自己是否是同一types的variables? 如果是这样的话,你可以使用rapply或unlist,因为data.frames是列表,内心深处…

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

可以用“扫描”读取它,或者在matrix上执行as.vector()。 如果您想按行或列,您可能需要首先转置matrix。 到目前为止张贴的解决scheme是如此粗糙,我甚至不会去尝试他们…

 > 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 

尝试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 

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

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

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

这可能是如此之晚,无论如何,这是我的方式转换matrix向量:

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

希望会有所帮助

你可以使用Joshua的解决scheme,但我认为你需要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是一个1d向量。

简单而快速,因为1d数组本质上是一个向量

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

如果你有一个data.frame(df)有多个列,你想vector化,你可以做

as.matrix(df,ncol = 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) 

第一个解决scheme使用as.vector() ,第二个解决scheme使用matrix存储为内存中的连续数组,并且length(m)给出matrixm中元素的数量。 第三个从x实例化一个array ,第四个使用连接函数c() 。 我也尝试了gdata unmatrix ,但是在这里提到的太慢了。

以下是我获得的一些数值结果:

 > 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 

平坦化matrix是机器学习中常见的操作,其中matrix可以表示要学习的参数,但是使用来自通用库的优化algorithm,该algorithm期望向量参数。 所以将matrix(或者matrix)转换成这样一个向量是很常见的。 标准R函数optim()就是这种情况。