Define multiple values as missing in a data frame

时间:2017-11-26 12:38:05

标签: r dataframe multiple-columns missing-data

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 个答案:

答案 0 :(得分:2)

以下是三种解决方案:

# 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)

答案 1 :(得分:1)

这应该有效

> 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

您可以使用上面的方法来指定缺少值标识符的对象,而不是table参数。