charlie090
charlie090

Reputation: 368

r: get columns that only have NaN value

sample code:

df:

#                        a                       b                       c
# 1 -0.0010616345688829504  -4.1135727372109387e-05 -0.0001814242939304348

There is only 1 row and 3000+ columns.

I was wondering how I can select only the columns with NaN (of which there is as I have confirmed looking at the data.) Would also be great if with NA as well if the code is significantly different.

I tried using is.nan but it didnt go so well. I was previously using df,which(df[1,]== some value)] for other values like numerics and logicals but doesnt work with NaN and NA.

Expecting something like this:

res:

#   d                                              
# 1 NaN                                             

Upvotes: 0

Views: 63

Answers (2)

rg255
rg255

Reputation: 4169

For a very simple solution pass a logical vector in base R

df[, is.na(df)]

This returns columns with NA and NaN

Upvotes: 0

akrun
akrun

Reputation: 887251

We can use Filter

Filter(function(x) is.nan(x), df)
#   d
#1 NaN

It may be better to do unlist as there is only a single row

df[is.nan(unlist(df))]

is.nan would give FALSE for NA while is.na gives TRUE for both

is.nan(c(NA, NaN))
#[1] FALSE  TRUE
is.na(c(NA, NaN))
#[1] TRUE TRUE

data

df <- data.frame(a = -0.0010616345688829504, 
    b = -4.1135727372109387e-05, c =  -0.0001814242939304348, d = NaN)

Upvotes: 1

Related Questions