假设我有一个矩阵A
[,1] [,2] [,3] [,4] [,5] [,6]
A 0 1 2 3 4 5
6 7 8 9 8 9
如何将其转换为R中的n x 4矩阵?第一列是常量,第二列是行id,第三列是列id,第四列是单元格值。例如
Z [,1] [,2] [,3] [,4]
[1,] A 1 1 0
[2,] A 1 2 1
[3,] A 1 3 2
[4,] A 1 4 3
[5,] A 1 5 4
[6,] A 1 6 5
[7,] A 2 1 6
[8,] A 2 2 7
[9,] A 2 3 8
[10,] A 2 4 9
[11,] A 2 5 8
[12,] A 2 6 9
我尝试了很少的功能,申请等等,但结果并没有接近我的预期。
答案 0 :(得分:0)
在R中,这样的事情会起作用。
A <- matrix(c(0:9, 8, 9), 2, byrow = TRUE) ## your matrix
tA <- t(A)
cbind("A", c(col(tA)), c(row(tA)), c(tA))
# [,1] [,2] [,3] [,4]
# [1,] "A" "1" "1" "0"
# [2,] "A" "1" "2" "1"
# [3,] "A" "1" "3" "2"
# [4,] "A" "1" "4" "3"
# [5,] "A" "1" "5" "4"
# [6,] "A" "1" "6" "5"
# [7,] "A" "2" "1" "6"
# [8,] "A" "2" "2" "7"
# [9,] "A" "2" "3" "8"
# [10,] "A" "2" "4" "9"
# [11,] "A" "2" "5" "8"
# [12,] "A" "2" "6" "9"
答案 1 :(得分:0)
虽然理查德的回答非常简洁,但你可能没有这些功能 让我们的伪代码:
# looks like python
init_A = yourmatrixA
init_R = Matrix.init(4, init_A.nrow*init_A.ncol) # ncol = get number of columns
C = constant
count = 1
rown = 1
for current_row in init_A.rows:
coln = 1
for current_col in current_row: # Assumes current_row is a list
init_R.set(count, 1, C) # set constant in first row
init_R.set(count, 2, rown)
init_R.set(count, 3, coln)
init_R.set(count, 4, current_col) # current_col is a value
coln += 1
count += 1
rown += 1
init_R.print()
未经测试
答案 2 :(得分:0)
此外:
dimnames(A) <- list(row=1:nrow(A),col=1:ncol(A))
cbind(id="A",as.data.frame.table(A,responseName="value"))
# id row col value
#1 A 1 1 0
#2 A 2 1 6
#3 A 1 2 1
#4 A 2 2 7
#5 A 1 3 2
#6 A 2 3 8
#7 A 1 4 3
#8 A 2 4 9
#9 A 1 5 4
#10 A 2 5 8
#11 A 1 6 5
#12 A 2 6 9
答案 3 :(得分:0)
使用melt
library(reshape2)
cbind(id='A', melt(A))
#it is better to have the result as a `data.frame`
#as there are `character` columns too
#If you want it as `matrix`, use `as.matrix`
as.matrix(cbind(id='A', melt(A)))
#Note that now all the `columns are `character` class