from.. 2011-02-01 11:52 采纳率: 100%
浏览 1717
已采纳

删除 data.frame 中带有所有或部分 NAs (缺失值)的行

I'd like to remove the lines in this data frame that:

a) contain NAs across all columns. Below is my example data frame.

             gene hsap mmul mmus rnor cfam
1 ENSG00000208234    0   NA   NA   NA   NA
2 ENSG00000199674    0   2    2    2    2
3 ENSG00000221622    0   NA   NA   NA   NA
4 ENSG00000207604    0   NA   NA   1    2
5 ENSG00000207431    0   NA   NA   NA   NA
6 ENSG00000221312    0   1    2    3    2

Basically, I'd like to get a data frame such as the following.

             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

b) contain NAs in only some columns, so I can also get this result:

             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
4 ENSG00000207604    0   NA   NA   1    2
6 ENSG00000221312    0   1    2    3    2

转载于:https://stackoverflow.com/questions/4862178/remove-rows-with-all-or-some-nas-missing-values-in-data-frame

  • 写回答

15条回答 默认 最新

  • Lotus@ 2011-02-01 12:21
    关注

    Also check complete.cases :

    > final[complete.cases(final), ]
                 gene hsap mmul mmus rnor cfam
    2 ENSG00000199674    0    2    2    2    2
    6 ENSG00000221312    0    1    2    3    2
    

    na.omit is nicer for just removing all NA's. complete.cases allows partial selection by including only certain columns of the dataframe:

    > final[complete.cases(final[ , 5:6]),]
                 gene hsap mmul mmus rnor cfam
    2 ENSG00000199674    0    2    2    2    2
    4 ENSG00000207604    0   NA   NA    1    2
    6 ENSG00000221312    0    1    2    3    2
    

    Your solution can't work. If you insist on using is.na, then you have to do something like:

    > final[rowSums(is.na(final[ , 5:6])) == 0, ]
                 gene hsap mmul mmus rnor cfam
    2 ENSG00000199674    0    2    2    2    2
    4 ENSG00000207604    0   NA   NA    1    2
    6 ENSG00000221312    0    1    2    3    2
    

    but using complete.cases is quite a lot more clear, and faster.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码