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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With