MAO-EYE 2011-02-01 11:52 采纳率: 100%
浏览 401
已采纳

删除 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

  • 写回答

14条回答 默认 最新

  • 斗士狗 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.

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

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。