Define multiple values as missing in a data frame

落爺英雄遲暮 提交于 2021-02-09 15:02:53

问题


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?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/47496228/define-multiple-values-as-missing-in-a-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!