我有一个矩形矩阵(4行,16列),我试图将其转换为正方形(16行x 16列),额外不相关的行应填充零。
这
0 1 2 3 4 5 11 12 13 14 15 63 64 65 66 67
0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 1 0 1 1 0 0 0 0 1 0 0 0 0 0
2 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
要
0 1 2 3 4 5 11 12 13 14 15 63 64 65 66 67
0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 1 0 1 1 0 0 0 0 1 0 0 0 0 0
2 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
63 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
有关如何在r中执行此操作的任何建议都将非常有用。
答案 0 :(得分:2)
您可以使用原始矩阵的尺寸
添加必要的行d <- dim(x)
cn <- colnames(x)
rbind(x, matrix(0, diff(d), ncol(x), dimnames = list(cn[(d[1]+1):d[2]])))
其中x
是
x <-
structure(c(0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L,
0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L,
0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L,
0L, 0L, 1L), .Dim = c(4L, 16L), .Dimnames = list(c("0", "1",
"2", "3"), c("0", "1", "2", "3", "4", "5", "11", "12", "13",
"14", "15", "63", "64", "65", "66", "67")))