Catherine Laing
Catherine Laing

Reputation: 657

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.

Upvotes: 2

Views: 726

Answers (4)

Roberto
Roberto

Reputation: 181

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)

Upvotes: 1

jay.sf
jay.sf

Reputation: 72813

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

Upvotes: 2

Cettt
Cettt

Reputation: 11981

you have to use mutate_at:

newdf <- mydf %>%
   mutate_at(vars(matches("\\.a")), ~replace_na(., 0))

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388982

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

Upvotes: 3

Related Questions