简体   繁体   English

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

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

This is my datafrmae:这是我的数据:

library(mlbench)
data(BreastCancer)

df_1<-BreastCancer

I did some modifications and appears "Na"'s on "Bare.nuclei" column:我做了一些修改并在“Bare.nuclei”列中出现了“Na”:

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

I am learning how to use across() , where() and ifelse() functions to replace these NA's by 0 .我正在学习如何使用across()where()ifelse()函数将这些 NA 替换为0

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

What am I doing wrong?我究竟做错了什么?

The idea here is to go across where the columns are numerics , and if on these columns I have Nas I will replace by 111 , otherwhise mantain x.这里的想法是 go across列是numericswhere ,如果在这些列上我有Nas ,我将替换为111 ,否则 mantain x。

This can be done with the tidyr::replace_na() function instead of if_else .这可以使用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