Filly
Filly

Reputation: 733

R: Make all row values NA if one value is NA

I want to do the following. If one value in the row is NA, then replace all the values of a row in a data frame by NA. Example:

 df <- data.frame( id=c(NA,20,30,40,NA,60), value=c(15,NA,35,45,55,65))

The output would be

  id value
1 NA    NA
2 NA    NA
3 30    35
4 40    45
5 NA    NA
6 60    65

Upvotes: 1

Views: 3353

Answers (3)

Samuel Isaacson
Samuel Isaacson

Reputation: 375

In addition to what others have posted, you can use the complete.cases function:

df <- data.frame(id = c(NA, 20, 30, 40, NA, 60),
                 value = c(15, NA, 35, 45, 55, 65))
complete.cases(df)
## [1] FALSE FALSE  TRUE  TRUE FALSE  TRUE
df[complete.cases(df), ]
##   id value
## 3 30    35
## 4 40    45
## 6 60    65

and you can set the incomplete rows to NA:

df[!complete.cases(df), ] <- NA
df
##   id value
## 1 NA    NA
## 2 NA    NA
## 3 30    35
## 4 40    45
## 5 NA    NA
## 6 60    65

Upvotes: 3

Neal Fultz
Neal Fultz

Reputation: 9696

If you are comfortable with the apply function:

R>df[ apply(is.na(df), 1, any), ] <- NA
R>df
  id value
1 NA    NA
2 NA    NA
3 30    35
4 40    45
5 NA    NA
6 60    65

Upvotes: 1

akrun
akrun

Reputation: 887951

You can try

df[!!rowSums(is.na(df)),] <- NA
df
#  id value
#1 NA    NA
#2 NA    NA
#3 30    35
#4 40    45
#5 NA    NA
#6 60    65

Or

df[with(df, is.na(id)|is.na(value)),] <- NA

Upvotes: 4

Related Questions