如何识别哪些列不是“NA”?矩阵中的每行?
我有一个 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
我想知道每行哪些列不是“NA”,所以我想要得到的是这样的:
[1] 2,3
[2] 4
[3] 0
[4] 5
[5] 0
但如果我这样做 > 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")
}
但我得到一个错误: number of要替换的项目不是替换长度的倍数
有没有办法做到这一点?提前致谢
I have a matrix with 12 rows and 77 columns, but to simply lets use:
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
I want to know which columns are not "NA" per row, so what I would like to get would be something like:
[1] 2,3
[2] 4
[3] 0
[4] 5
[5] 0
but if I do > which(p[]!="NA")
I get [1] 6 11 17 24 32
I tried using a loop:
aux <- matrix(NA,5,7)
for(i in 1:5) {
aux[i,]<-which(p[i,]!="NA")
}
but I just get an error: number of items to replace is not a multiple of replacement length
Is there a way of doing this? Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
我认为这与您指定的输出一样信息丰富,并且可能比您指定的输出更有用,但如果您确实想要列表版本,那么可以使用:
或者甚至与粘贴一起涂抹:
which< 的输出/code> 函数建议的方法提供逻辑测试的非零 (TRUE) 位置的行和列:
如果没有将 arr.ind 参数设置为非默认 TRUE,您只能得到“向量位置”使用 R 的主要排序列确定作为其惯例。 R 矩阵只是“折叠向量”。
Try:
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
Or even with smushing together with paste:
The output from
which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:Without the
arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".