在R中删除Inf和NaN的行

时间:2014-04-02 07:32:21

标签: r dataframe

我有以下数据:

> 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

我想要做的是包含InfNan的行 仅返回NM_198411 Inf2 1.152414 1.445595

但为什么这段代码失败了?

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

1 个答案:

答案 0 :(得分:11)

您无法使用常规比较运算符检查NaN。您可以Inf执行此操作,但您还必须检查否定的情况。最好使用其中一个功能:https://stat.ethz.ch/R-manual/R-devel/library/base/html/is.finite.html

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

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