首页 > 解决方案 > 使用 dplyr、cross()、where() 和 if_else() 函数将 NA 替换为数字

问题描述

这是我的datafrmae:

library(mlbench)
data(BreastCancer)

df_1<-BreastCancer

我做了一些修改,并在“Bare.nuclei”列上出现了“Na”:

df_1<-df_1 %>% mutate(across(where(~is.factor(.x)),as.numeric)) 

我正在学习如何使用across(),where()以及ifelse()将这些 NA 替换为0.

df_1 %>% mutate(across(where(~ is.numeric(.x)), if_else(is.na(.x,0,.x))))

我究竟做错了什么?

这里的想法是across where列是numerics,如果在这些列上Nas我将替换为111,否则将替换为 mantain x。

标签: rdplyr

解决方案


这可以通过tidyr::replace_na()函数而不是if_else.

df_1 %>% mutate(across(where(~ is.numeric(.x)), function(x){replace_na(x, 0)}))

推荐阅读