program story

행렬을 1 차원 배열로 변환

inputbox 2020. 8. 17. 08:53
반응형

행렬을 1 차원 배열로 변환


매트릭스 (32X48)가 있습니다.

행렬을 1 차원 배열로 어떻게 변환 할 수 있습니까?


'스캔'으로 읽거나 행렬에서 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

data.frame에 대해 이야기하고 있다면 같은 유형의 변수인지 스스로에게 물어봐야합니다. 그렇다면 데이터 프레임은 목록이므로 영혼 깊은 곳에있는 rapply 또는 unlist를 사용할 수 있습니다.

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

시험 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

From ?matrix: "행렬은 2 차원 '배열'의 특별한 경우입니다." 행렬 / 배열의 크기를 간단히 변경할 수 있습니다.

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

array(A)또는 array(t(A))1 차원 배열을 제공합니다.


너무 늦었을 수도 있습니다. 어쨌든 Matrix를 벡터로 변환하는 방법은 다음과 같습니다.

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

도움이 되길 바랍니다


사용할 수 있습니다 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. 세 번째는 arrayfrom을 인스턴스화 x하고 네 번째는 연결 함수를 사용합니다 c(). 나는 또한 시도 unmatrix에서 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

Flattening a matrix is a common operation in Machine Learning, where a matrix can represent the parameters to learn but one uses an optimization algorithm from a generic library which expects a vector of parameters. So it is common to transform the matrix (or matrices) into such a vector. It's the case with the standard R function optim().


You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)

Or for loops:

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 is a 1d vector.


Simple and fast since a 1d array is essentially a vector

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

If you instead had a data.frame (df) that had multiple columns and you want to vectorize you can do

as.matrix(df, ncol=1)

참고URL : https://stackoverflow.com/questions/3823211/convert-a-matrix-to-a-1-dimensional-array

반응형