Why is across() not working like it should?

338 views Asked by At

I'm trying to understand how to use the across() function in order to replace _if, replace_at, variations. But I can't see why this code is not working. I've already checked the "colwise" vignette but it didn't help much.

hmeq <- read.csv("http://www.creditriskanalytics.net/uploads/1/9/5/1/19511601/hmeq.csv", 
sep = ",", 
header = TRUE)

replace_na_mean <- function(x){
  mean <- mean(x, na.rm = TRUE)
  x[is.na(x)] <- mean
  return(x)
}

hmeq %>% mutate(across(where(is.numeric), replace_na_mean)) #1
hmeq %>% mutate_if(is.numeric, replace_na_mean) %>% head() %>% DT::datatable()#2

#1 Output is basically the original data frame without any modifications, it's as if the code isn't doing anything.

Output without any changes to original df

#2 Is working but I'm trying to replace this with mutate() and across():

Output I want but using code #1

1

There are 1 answers

0
akrun On

The across is working fine

library(dplyr) # version - 1.0.1
out <- hmeq %>%
       mutate(across(where(is.numeric), replace_na_mean)) 

out %>%
     filter(BAD == 1, LOAN == 1500) %>% 
     pull(MORTDUE)
  #[1] 13500.00 73760.82