【问题标题】:Fill NAs with 0 if the column is numeric and empty string '' if the column is a factor using R [duplicate]如果列是数字,则用 0 填充 NA,如果列是使用 R 的因子,则使用空字符串 '' [重复]
【发布时间】:2020-10-29 16:37:31
【问题描述】:

我正在尝试将整数类型列中存在的所有 NA 替换为 0,并将因子类型列中存在的 NA 替换为空字符串“”。下面的代码是我正在使用的代码,但它似乎不起作用

for(i in 1:ncol(credits)){
if(sapply(credits[i], class) == 'integer'){
    credits[is.na(credits[,i]), i] <- 0
}
else if(sapply(credits[i], class) == 'factor'){
    credits[is.na(credits[,i]), i] <- ''
}

【问题讨论】:

标签: r dataframe na


【解决方案1】:

您可以在dplyr 中使用across 将列值替换为class

library(dplyr)

df %>%
  mutate(across(where(is.factor), ~replace(as.character(.), is.na(.), '')),
         across(where(is.numeric), ~replace(., is.na(.), 0)))


#  a b
#1 1 a
#2 2 b
#3 0 c
#4 4 d
#5 5  

b 列现在属于“字符”类,如果您需要它为factor,您可以在replace 之外添加factor,例如:

across(where(is.factor), ~factor(replace(as.character(.), is.na(.), ''))),

数据

df <- data.frame(a = c(1, 2, NA, 4:5), b = c(letters[1:4], NA), 
                 stringsAsFactors = TRUE)

【讨论】:

    【解决方案2】:

    实现相同目的的另一种方法:

    library(dplyr)
    
    # Dataframe
    df <- data.frame(x = c(1, 2, NA, 4:5), y = c('a',NA, 'd','e','f'), 
                 stringsAsFactors = TRUE)
    
    # Creating new columns
    df_final<- df %>% 
      mutate(new_x = ifelse(is.numeric(x)==TRUE & is.na(x)==TRUE,0,x)) %>% 
      mutate(new_y = ifelse(is.factor(y)==TRUE & is.na(y)==TRUE,"",y))
    
    # Printing the output
    df_final
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2018-03-06
      • 2021-07-27
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多