Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NAs in columns with specific variable names

I have a dataframe with 14 columns. 12 of the columns end with the variable name .T, and I want to replace NAs with 0 in these columns only. I've tried using mutate_if() as suggested in this post, but I get the error message Error: No tidyselect variables were registered Callrlang::last_error()to see a backtrace.

My code (with sample data) is as follows:

 library(tibble)

 mydf <- tribble(~Var1, ~Var2.a, ~Var3.a,
                 "A", NA, 1,
                 NA, NA, NA,
                 "C", 3, 3,
                 NA, NA, NA)

 newdf <- mydf %>%
   mutate_if(contains(".a"), ~replace_na(., 0))

Error: No tidyselect variables were registered Call rlang::last_error() to see a backtrace

I'd like to use dplyr if possible.

like image 242
Catherine Laing Avatar asked Aug 08 '26 09:08

Catherine Laing


1 Answers

You should use mutate_at, also include the column name in vars()

library(dplyr)
mydf %>% mutate_at(vars(contains(".a")), replace_na, 0)

#  Var1  Var2.a Var3.a
#  <chr>  <dbl>  <dbl>
#1 A          0      1
#2 NA         0      0
#3 C          3      3
#4 NA         0      0
like image 180
Ronak Shah Avatar answered Aug 10 '26 22:08

Ronak Shah