2

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.

Cettt
  • 11,460
  • 7
  • 35
  • 58
Catherine Laing
  • 475
  • 6
  • 18
  • 1
    **Self promotion**: `mde::recode_na_as(mydf,0,subset_df=T,tidy=T,pattern_type="ends_with",pattern=".a")` – NelsonGon Mar 05 '20 at 11:23

4 Answers4

3

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

you have to use mutate_at:

newdf <- mydf %>%
   mutate_at(vars(matches("\\.a")), ~replace_na(., 0))
Cettt
  • 11,460
  • 7
  • 35
  • 58
2

In base R you may use grep.

r <- grep("\\.a", names(mydf))
mydf[r][is.na(mydf[r])] <- 0

# # A tibble: 4 x 3
#   Var1  Var2.a Var3.a
#   <chr>  <dbl>  <dbl>
# 1 A          0      1
# 2 NA         0      0
# 3 C          3      3
# 4 NA         0      0
jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

The simplest way is to use is.na. For example:

df$x[is.na(df$x] <- 0

You can also do this for multiple columns at once using df[,2:6] (e.g. columns 2 through 6)

Roberto
  • 181
  • 8