Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define multiple values as missing in a data frame

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?

like image 431
Ole Avatar asked Mar 13 '26 04:03

Ole


1 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)
like image 124
Andrii Avatar answered Mar 15 '26 17:03

Andrii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!