Guillermo.D
Guillermo.D

Reputation: 447

Extract row values where NaN is present in R

This may be a very easy question but I already have been dealing with it for some time.

I have a data frame where column X have some "NaN" values. I need to extract the row values of columns A and B when X is "NaN" and put these in a new data frame.

I think the solution should be something similar to this if-statement but it doesn't work:

X = df$X
A = df$A 
B = df$B 

NaNvalues <- if (is.nan(X)) {
  data.frame(A, B)
}

Upvotes: 2

Views: 1123

Answers (2)

svenhalvorson
svenhalvorson

Reputation: 1080

You can use the which function:

nans <- which(is.na(X))

You also probably want to make sure you're using NaN/NA appropriately. is.na and is.nan are a little bit different. This post cleared it up for me.

Upvotes: 0

ikop
ikop

Reputation: 1790

new_df <- df[is.nan(df$X), c("A","B")]

should give you what you are looking for. Here, you use the vector of indices where the column X is NaN (generated by is.nan(df$X) to index the rows in your data frame.

Upvotes: 3

Related Questions