通过 NA 为 DataFrame 中的所有列查找和替换值

Find and replace values by NA for all columns in DataFrame

Age <- c(90,56,51,'NULL',67,'NULL',51)
Sex <- c('Male','Female','NULL','male','NULL','Female','Male')
Tenure <- c(2,'NULL',3,4,3,3,4)
df <- data.frame(Age, Sex, Tenure)

在上面的示例中,有 'NULL' 个值作为 character/string 甲酸盐。 我试图用 NA 代替 'NULL' 值。我能够将它作为单个列作为 df$age[which(df$Age=='NULL)]<-NA' 但是我不想为所有列写这个。

如何将类似的逻辑应用于所有列,以便将 df 的所有 'NULL' 值转换为 NAs?我猜 apply 或自定义函数或 for 循环会做到这一点。

我们可以用dplyrreplace所有列中的'NULL'值,然后用type.convert转换列的类型。目前所有的列都是factorclass(假设'Age/Tenure'应该是numeric/integerclass)

library(dplyr)
res <- df %>%
         mutate_all(funs(type.convert(as.character(replace(., .=='NULL', NA)))))
str(res)
#'data.frame':   7 obs. of  3 variables:
#$ Age   : int  90 56 51 NA 67 NA 51
#$ Sex   : Factor w/ 3 levels "Female","male",..: 3 1 NA 2 NA 1 3
#$ Tenure: int  2 NA 3 4 3 3 4

基础 R 解决方案

replace(df, df =="NULL", NA)

甚至可以一步替换:

df[df=="NULL"] <- NA