Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove rows with Inf and NaN in R

Tags:

dataframe

r

I have the following data:

> 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

What I want to do is to rows that contain Inf and Nan returning only 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) ),]
like image 413
pdubois Avatar asked Apr 02 '14 07:04

pdubois


1 Answers

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

Edit: 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), ]
like image 170
Marco Avatar answered Oct 05 '22 23:10

Marco