Define multiple values as missing in a data frame

Viewed 1869

How do I define multiple values as missing in a data frame in R?

Consider a data frame where two values, "888" and "999", represent missing data:

df <- data.frame(age=c(50,30,27,888),insomnia=c("yes","no","no",999))
df[df==888] <- NA
df[df==999] <- NA

This solution takes one line of code per value representing missing data. Do you have a more simple solution for situations where the number of values representing missing data is high?

2 Answers

Here are three solutions:

# 1. Data set
df <- data.frame(
  age = c(50, 30, 27, 888),
  insomnia = c("yes", "no", "no", 999))

# 2. Solution based on "one line of code per missing data value"
df[df == 888] <- NA
df[df == 999] <- NA
is.na(df)

# 3. Solution based on "applying function to each column of data set"
df[sapply(df, function(x) as.character(x) %in% c("888", "999") )] <- NA
is.na(df)

# 4. Solution based on "dplyr"

# 4.1. Load package
library(dplyr)

# 4.2. Define function for missing values
is_na <- function(x){
 return(as.character(x) %in% c("888", "999")) 
}

# 4.3. Apply function to each column
df %>% lapply(is_na)

This should work

> rm(list = ls())
> df1 <- df2 <- 
+   data.frame(age=c(50,30,27,888),insomnia=c("yes","no","no",999))
> df1[df1==888] <- NA
> df1[df1==999] <- NA
> 
> df2[sapply(df2, "%in%", table = c(888, 999))] <- NA
> all.equal(df1, df2)
[1] TRUE

You can use the above where you assign an object of missing values identifiers which you than pass as the table argument.

Related