[英]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
列是numerics
的where
,如果在这些列上我有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.