Spa*_*man 202
要么使用'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
Run Code Online (Sandbox Code Playgroud)
aL3*_*3xa 29
如果我们谈论的是data.frame,那么你应该问自己是同一类型的变量吗?如果是这种情况,你可以使用rapply或unlist,因为data.frames是列表,在他们的灵魂深处......
data(mtcars)
unlist(mtcars)
rapply(mtcars, c) # completely stupid and pointless, and slower
Run Code Online (Sandbox Code Playgroud)
Gre*_*reg 29
尝试 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
Run Code Online (Sandbox Code Playgroud)
Jos*_*ich 12
来自?matrix:"矩阵是二维'数组'的特例." 您只需更改矩阵/数组的尺寸即可.
Elts_int <- as.matrix(tmp_int) # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)
Run Code Online (Sandbox Code Playgroud)
你可以使用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)
Run Code Online (Sandbox Code Playgroud)
第一个解决方案使用as.vector(),第二个使用矩阵作为连续数组存储在内存中的事实,并length(m)给出矩阵中元素的数量m。第三个实例化一个arrayfrom x,第四个使用 concatenate 函数c()。我也尝试过unmatrixfrom gdata,但是这里提到的太慢了。
下面是我得到的一些数值结果:
> 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
Run Code Online (Sandbox Code Playgroud)
展平矩阵是机器学习中的一种常见操作,其中矩阵可以表示要学习的参数,但使用通用库中的优化算法,该算法需要参数向量。所以通常将矩阵(或矩阵)转换为这样的向量。标准 R 函数就是这种情况optim()。
小智 5
简单快速,因为一维数组本质上是一个向量
result <- matrix[1:length(matrix)]
Run Code Online (Sandbox Code Playgroud)
可能这么晚了,无论如何,这是我将Matrix转换为vector的方式:
library(gdata)
vector_data<- unmatrix(yourdata,byrow=T))
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助