[R]벡터를 행렬로 변환(vector into matrix), 행렬을 벡터로 변환(vectorization)
R 분석과 프로그래밍/R 데이터 전처리 2016. 6. 9. 00:32이번 포스팅에서는 벡터(vector)와 행렬(matrix)를 자유자재로 넘나들며 데이터 변환하는 방법을 소개하겠습니다. R에는 벡터와 행렬을 아주 쉽게 넘나들게 해주는 함수가 있답니다.
(1) 벡터를 행렬로 변환하기
(1-1) 벡터를 열(column) 기준으로 행렬로 변환하기 : matrix(vector, byrow = FALSE, ncol = n)
(1-2) 벡터를 행(row) 기준으로 행렬로 변환하기 : matrix(vector, byrow = TRUE, ncol = n)
(2) 행렬을 벡터로 변환하기 (vectorization)
(2-1) 행렬을 열(column) 기준으로 벡터로 변환하기 : as.vector(matrix)
(2-2) 행렬을 행(row) 기준으로 벡터로 변환하기 : as.vector( t(matrix) )
(1) 벡터를 행렬로 변환하기 (converting vector into matrix)
(1-1) 벡터를 열(column) 기준으로 행렬로 변환하기
> ##------------------------------------------------------- > ## vector into matrix, matrix into vector (vectorization) > ##------------------------------------------------------- > > # input vector > vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) > vec [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 > > # (1-1) vector into matrix by column > matrix_bycol <- matrix(vec, byrow = F, ncol = 3) > matrix_bycol [,1] [,2] [,3] [1,] 1 6 11 [2,] 2 7 12 [3,] 3 8 13 [4,] 4 9 14 [5,] 5 10 15
|
(1-2) 벡터를 행(row) 기준으로 행렬로 변환하기
> # (1-2) vector into matrix by row > matrix_byrow <- matrix(vec, byrow = T, ncol = 3) > matrix_byrow [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [4,] 10 11 12 [5,] 13 14 15
|
(2) 행렬을 벡터로 변환하기 (vectorization, converting matrix into vector)
(2-1) 행렬을 열(column) 기준으로 벡터로 변환하기
> # (2-1) matrix into vector (vectorization) by column : as.vector() > matrix_bycol [,1] [,2] [,3] [1,] 1 6 11 [2,] 2 7 12 [3,] 3 8 13 [4,] 4 9 14 [5,] 5 10 15 > vectorization_bycol <- as.vector(matrix_bycol) > vectorization_bycol [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
(2-2) 행렬을 행(row) 기준으로 벡터로 변환하기
> # (2-2) matrix into vector (vectorization) by row : as.vector(t()) > matrix_bycol [,1] [,2] [,3] [1,] 1 6 11 [2,] 2 7 12 [3,] 3 8 13 [4,] 4 9 14 [5,] 5 10 15 > vectorization_byrow <- as.vector(t(matrix_bycol)) > vectorization_byrow [1] 1 6 11 2 7 12 3 8 13 4 9 14 5 10 15 |
이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡'를 꾸욱 눌러주세요. ^^
댓글을 달아 주세요
안녕하세요? 주인장님
(2-2) 에서 아래와 예시와 같이 행이름과 열이름을 포함해서 세로로 표현할 방법이 있을까요?
[1,]-[,1] 1
[1,]-[,2] 6
[1,]-[,3] 11
[2,]-[,1] 2
...
안녕하세요 ks님,
아래 코드 참고하시기 바랍니다.
##=======================
## matrix, vectorization
##=======================
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
matrix_bycol <- matrix(vec, byrow = F, ncol = 3)
matrix_bycol
# [,1] [,2] [,3]
# [1,] 1 6 11
# [2,] 2 7 12
# [3,] 3 8 13
# [4,] 4 9 14
# [5,] 5 10 15
row_num <- nrow(matrix_bycol)
col_num <- ncol(matrix_bycol)
for (i in 1:row_num){
for (j in 1:col_num){
print(paste0('[', row_num, ',]-[,', col_num, '] ', matrix_bycol[i, j]))
}
}
# [1] "[5,]-[,3] 1"
# [1] "[5,]-[,3] 6"
# [1] "[5,]-[,3] 11"
# [1] "[5,]-[,3] 2"
# [1] "[5,]-[,3] 7"
# [1] "[5,]-[,3] 12"
# [1] "[5,]-[,3] 3"
# [1] "[5,]-[,3] 8"
# [1] "[5,]-[,3] 13"
# [1] "[5,]-[,3] 4"
# [1] "[5,]-[,3] 9"
# [1] "[5,]-[,3] 14"
# [1] "[5,]-[,3] 5"
# [1] "[5,]-[,3] 10"
# [1] "[5,]-[,3] 15"
주인장님 감사합니다.