我的邻接矩阵如下:
> matrix(c(0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0),ncol=4,byrow=T)
[,1] [,2] [,3] [,4]
[1,] 0 1 0 0
[2,] 1 0 1 0
[3,] 0 1 0 1
[4,] 0 0 1 0
问题1:如何获得类似的信息:
2 5 7 10 12 15
来自R?
问题2:如何获取每行中“ 1”的位置信息,如:
2
1 3
2 4
3
还是2 1 3 2 4 3
来自R?
谢谢!
答案 0 :(得分:0)
只需在逻辑矩阵上使用which
which(m1 == 1)
#[1] 2 5 7 10 12 15
如果我们需要list
中的列索引
sapply(split(!!m1, col(m1)), which)
或作为矢量
na.omit(na_if(c(t(m1 * col(m1))), 0))
#[1] 2 1 3 2 4 3
m1 <- matrix(c(0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0),ncol = 4,byrow = TRUE)
答案 1 :(得分:0)
m <- matrix(c(0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0),ncol=4,byrow=T)
mm <- m == 1
which(mm)
#[1] 2 5 7 10 12 15
apply(mm, 1, which)
#[[1]]
#[1] 2
#
#[[2]]
#[1] 1 3
#
#[[3]]
#[1] 2 4
#
#[[4]]
#[1] 3
也许还会看到raster::adjacency