如何识别矩阵中每行不是"NA"的列?

sbg*_*sbg 12 r matrix

我有一个12行和77列的​​矩阵,但只是让我们使用:

p <- matrix(NA,5,7)  
p[1,2]<-0.3  
p[1,3]<-0.5  
p[2,4]<-0.9  
p[2,7]<-0.4  
p[4,5]<-0.6 
Run Code Online (Sandbox Code Playgroud)

我想知道每行哪些列不是"NA",所以我想得到的是:

[1] 2,3  
[2] 4  
[3] 0  
[4] 5  
[5] 0 
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,> which(p[]!="NA")我会[1] 6 11 17 24 32

我尝试使用循环:

aux <- matrix(NA,5,7)  
for(i in 1:5) {  
    aux[i,]<-which(p[i,]!="NA")  
}
Run Code Online (Sandbox Code Playgroud)

但我只是得到一个错误: number of items to replace is not a multiple of replacement length

有办法做到这一点吗?提前致谢

42-*_*42- 25

尝试:

which( !is.na(p), arr.ind=TRUE)
Run Code Online (Sandbox Code Playgroud)

我认为这与您指定的输出一样具有信息性,可能更有用,但如果您真的想要列表版本,那么可以使用:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)
Run Code Online (Sandbox Code Playgroud)

或者甚至与粘贴一起涂抹:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
Run Code Online (Sandbox Code Playgroud)

which函数的输出建议方法提供逻辑测试的非零(TRUE)位置的行和列:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7
Run Code Online (Sandbox Code Playgroud)

如果没有将arr.ind参数设置为非默认值TRUE,则只能使用R具有的列主要顺序来确定"向量位置".R矩阵只是"折叠向量".

> which( !is.na(p) )
[1]  6 11 17 24 32
Run Code Online (Sandbox Code Playgroud)