假設我有一個稀疏的 m x n 二進制矩陣,并且我已經使用行索引串列來表示這些。例如,下面的 3×3 矩陣
[,1] [,2] [,3]
[1,] 1 1 0
[2,] 0 1 0
[3,] 0 0 1
由串列 M_row 表示:
> M_row
[[1]]
[1] 1 2
[[2]]
[1] 2
[[3]]
[1] 3
這里串列中的第 i 個元素對應于第 i 行中元素的位置。我想將此串列轉換為列索引串列,其中新串列中的第 j 個元素對應于第 j 列中的元素的(行)位置。對于前面的示例,我想要:
> M_col
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 3
有沒有一種有效的方法可以在不撰寫很多回圈的情況下做到這一點?
uj5u.com熱心網友回復:
嘗試這個
M_row <- list(1:2 , 2, 3) # this is the beginning list
#----------------------------------
m <- matrix(0 , length(M_row) , length(M_row))
for(i in 1:nrow(m)) {
m[ i , M_row[[i]]] <- 1
}
M_col <- apply(m , 2 , \(x) which(x == 1))
#----------------------------------
M_col # this is the required list
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 1 2
#>
#> [[3]]
#> [1] 3
uj5u.com熱心網友回復:
這是一個不創建矩陣的演算法。
- 獲取列數
sapply/max
并創建M_col
所需長度的結果串列; - 對于每個輸入串列成員,
M_col
通過將行號附加到它來進行更新。
M_row <- list(1:2 , 2, 3)
Max_col <- max(sapply(M_row, max))
M_col <- vector("list", length = Max_col)
for(i in seq_along(M_row)) {
for(j in M_row[[i]]) {
M_col[[j]] <- c(M_col[[j]], i)
}
}
M_col
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 1 2
#>
#> [[3]]
#> [1] 3
由reprex 包于 2022-06-19 創建(v2.0.1)
uj5u.com熱心網友回復:
你可以使用stack
unstack
:
M_row <- list(1:2 , 2, 3) # this is the beginning list
d <- type.convert(stack(setNames(M_row, seq_along(M_row))), as.is = TRUE)
d
values ind
1 1 1
2 2 1
3 2 2
4 3 3
d
是行、列組合,其中values
代表行,而ind
代表列:
列式:
unstack(d, ind~values)
$`1`
[1] 1
$`2`
[1] 1 2
$`3`
[1] 3
逐行:
unstack(d, values~ind)
$`1`
[1] 1 2
$`2`
[1] 2
$`3`
[1] 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/493747.html