【问题标题】:How to identify which columns are not "NA" per row in a matrix?如何识别矩阵中每行哪些列不是“NA”?
【发布时间】:2011-09-16 18:06:23
【问题描述】:

我有一个 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 

但是如果我这样做&gt; 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 items to replace is not a multiple of replacement length

有没有办法做到这一点?在此先感谢

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    试试:

    which( !is.na(p), arr.ind=TRUE)
    

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

    > 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)
    

    甚至与糊状物一起涂抹:

    lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
    

    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
    

    如果不将 arr.ind 参数设置为非默认 TRUE,则您只能使用 R 的列主排序作为其约定来确定“向量位置”。 R 矩阵只是“折叠向量”。

    > which( !is.na(p) )
    [1]  6 11 17 24 32
    

    【讨论】:

    • 最后可以为 length() > 0 添加检查以返回 0 而不是 integer(0)。
    • lapply ,collapse 输出产生空字符元素"",而不是笨重的'integer(0)'。
    • 如果是数据框而不是矩阵,如何获取列名?
    • @PolarBear 似乎是一个不同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2020-01-07
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多