使用Inf和NaN在R中删除行 [英] Remove rows with Inf and NaN in R

查看:1199
本文介绍了使用Inf和NaN在R中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

> dat
               ID     Gene   Value1   Value2
1      NM_013468   Ankrd1       Inf      Inf
2      NM_023785     Ppbp       Inf      Inf
3      NM_178666   Themis       NaN      Inf
4   NM_001161790     Mefv       Inf      Inf
5   NM_001161791     Mefv       Inf      Inf
6      NM_019453     Mefv       Inf      Inf
7      NM_008337     Ifng       Inf      Inf
8      NM_022430   Ms4a8a       Inf      Inf
9  PBANKA_090410     Rab6       NaN      Inf
10     NM_011328      Sct       Inf      Inf
11     NM_198411     Inf2  1.152414 1.445595
12     NM_177363    Tarm1       NaN      Inf
13  NM_001136068    Klrc1       NaN      Inf
14     NM_019418  Tnfsf14       Inf      Inf
15     NM_010652    Klrc1       NaN      Inf

我想做的是包含 Inf Nan
只返回 NM_198411 Inf2 1.152414 1.445595

但是为什么这个代码失败?

But why this code failed?

dat <- structure(list(ID = structure(c(7L, 11L, 13L, 2L, 3L, 9L, 4L, 
10L, 15L, 6L, 14L, 12L, 1L, 8L, 5L), .Label = c("NM_001136068 ", 
"NM_001161790 ", "NM_001161791 ", "NM_008337 ", "NM_010652 ", 
"NM_011328 ", "NM_013468 ", "NM_019418 ", "NM_019453 ", "NM_022430 ", 
"NM_023785 ", "NM_177363 ", "NM_178666 ", "NM_198411 ", "PBANKA_090410 "
), class = "factor"), Gene = structure(c(1L, 7L, 11L, 5L, 5L, 
5L, 2L, 6L, 8L, 9L, 3L, 10L, 4L, 12L, 4L), .Label = c("Ankrd1 ", 
"Ifng ", "Inf2 ", "Klrc1 ", "Mefv ", "Ms4a8a ", "Ppbp ", "Rab6 ", 
"Sct ", "Tarm1 ", "Themis ", "Tnfsf14 "), class = "factor"), 
    Value1 = c(Inf, Inf, NaN, Inf, Inf, Inf, Inf, Inf, NaN, Inf, 
    1.152414042, NaN, NaN, Inf, NaN), Value2 = c(Inf, Inf, Inf, 
    Inf, Inf, Inf, Inf, Inf, Inf, Inf, 1.445594931, Inf, Inf, 
    Inf, Inf)), .Names = c("ID", "Gene", "Value1", "Value2"), class = "data.frame", row.names = c(NA, 
-15L))


dat[apply(dat,1,function(x) any(x >=1 | x != Inf | x != NaN) ),]


推荐答案

用正常的比较运算符检查 NaN 。您可以为 Inf 执行此操作,但您也必须检查否定的情况。更好地使用以下功能之一: https ://stat.ethz.ch/R-manual/R-devel/library/base/html/is.finite.html

You can't check for NaN with the normal compare operators. You can do so for Inf, but you would also have to check for the negative case. Better to use one of those functions: https://stat.ethz.ch/R-manual/R-devel/library/base/html/is.finite.html

编辑:tonytonov指出, is.finite(NaN) FALSE ,这在这种情况下足以使用。因此,您只需要

tonytonov pointed out, that is.finite(NaN) is FALSE, which makes it sufficient to use in this case. You therefore just need

dat[is.finite(dat$Value1) & is.finite(dat$Value2), ]

这篇关于使用Inf和NaN在R中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆