繁体   English   中英

使用 dplyr、across()、where() 和 if_else() 函数将 NA 替换为数字

[英]Using dplyr, across(), where() and if_else() functions to replace NA by a number

这是我的数据:

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))))

我究竟做错了什么?

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

这可以使用tidyr::replace_na() function 而不是if_else来完成。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM