繁体   English   中英

R:如何将由行索引列表表示的稀疏二进制矩阵转换为列索引列表

[英]R: how to convert a sparse binary matrix represented by row-indexed lists to column-indexed lists

假设我有一个稀疏的 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

有没有一种有效的方法可以在不编写很多循环的情况下做到这一点?

尝试这个

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

这是一个不创建矩阵的算法。

  1. 使用sapply/max获取列数,并创建所需长度的结果列表M_col
  2. 对于每个输入列表成员,通过将行号附加到它来更新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)

你可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM