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

问题描述 投票:2回答:3
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'值作为字符/字符串格式。我试图用NA来代替'NULL'值。我能够将它作为单个列作为df$age[which(df$Age=='NULL)]<-NA'然而我不想为所有列写这个。

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

r data-analysis na data-cleaning
3个回答
0
投票

我们可以使用dplyrreplace所有列中的'NULL'值,然后使用type.convert转换列的类型。目前,所有列都是factor类(假设'年龄/任期'应该是numeric/integer类)

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

9
投票

游泳池P solutine

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

3
投票

甚至可以用一步替换:

df[df=="NULL"] <- NA
© www.soinside.com 2019 - 2024. All rights reserved.