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

删除 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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。