簡體   English   中英

在R中刪除Inf和NaN的行

[英]Remove rows with Inf and NaN in 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

我想要做的是包含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) ),]

您無法使用常規比較運算符檢查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), ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM