[英]How to re-structure a matrix in R?
假設我在R中有一個5 x 5的矩陣,如下所示:
[,1] [,2] [,3] [,4] [,5]
1 0 1 1 0 1
2 1 0 0 1 0
3 0 0 0 1 0
4 1 0 1 0 1
5 1 0 0 0 0
我想將此矩陣重新設置為以下結構:
對於每一行,列出行號和每個包含元素1的關聯列索引。例如,如果使用上面的矩陣,我們將得到:
1, 2, 3, 5
2, 1, 4
3, 4
4, 1, 3, 5
5, 1
set.seed(42)
m = matrix(sample(0:1, 25, TRUE), 5, 5)
apply(m, 1, function(x) which(x == 1))
#[[1]]
#[1] 1 2 4 5
#[[2]]
#[1] 1 2 3 4
#[[3]]
#[1] 3 5
#[[4]]
#[1] 1 2 5
#[[5]]
#[1] 1 2 4
第二個選項使用which
和aggregate
out <- aggregate(col ~ row, which(m == 1, arr.ind = TRUE), c)
out
# row col
#1 1 1, 2, 4, 5
#2 2 1, 2, 3, 4
#3 3 3, 5
#4 4 1, 2, 5
#5 5 1, 2, 4
(雖然不確定這是否是您的預期輸出)
str(out)
#'data.frame': 5 obs. of 2 variables:
# $ row: int 1 2 3 4 5
# $ col:List of 5
# ..$ 1: int 1 2 4 5
# ..$ 2: int 1 2 3 4
# ..$ 3: int 3 5
# ..$ 4: int 1 2 5
# ..$ 5: int 1 2 4
數據
取自@Telepresence
set.seed(42)
m = matrix(sample(0:1, 25, TRUE), 5, 5)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 1 0 1 1
#[2,] 1 1 1 1 0
#[3,] 0 0 1 0 1
#[4,] 1 1 0 0 1
#[5,] 1 1 0 1 0
一個選項被split
with(as.data.frame(which(m == 1, arr.ind = TRUE)), split(col, row))
#$`1`
#[1] 1 2 4 5
#$`2`
#[1] 1 2 3 4
#$`3`
#[1] 3 5
#$`4`
#[1] 1 2 5
#$`5`
#[1] 1 2 4
或tapply
tapply(as.logical(m), row(m), FUN = which)
#$`1`
#[1] 1 2 4 5
#$`2`
#[1] 1 2 3 4
#$`3`
#[1] 3 5
#$`4`
#[1] 1 2 5
#$`5`
#[1] 1 2 4
或使用row
split
split(m * col(m), row(m))
並刪除0
lapply(split(m * col(m), row(m)), setdiff, 0)
注意:所有解決方案均有效。
m <- structure(c(1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1,
0, 0, 1, 1, 0, 1, 1, 0), .Dim = c(5L, 5L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.