-1

I am trying to replace NA with 0 for some specific variables irrespective of their positions. i wrote below code, but getting some error..

data1[, starts_with("Year_")][is.na(data1[, starts_with("Year_")])] <- 0

i got the below error

Error: No tidyselect variables were registered 

Call `rlang::last_error()` to see a backtrace

I have installed dplyr, tidyr, tidyselect, but still i am getting this error, can anyone help me on this matter.

Tushar Lad
  • 490
  • 1
  • 4
  • 17
  • 2
    If you add a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610), you could make it easier for others to find and test a answer to your question. That way you can help others to help you! – dario Mar 09 '20 at 12:23
  • If you are using base R try `startsWith("Year_", names(data1))`. the tidyhelper `starts_with()` is typically used within the `select()` function within a pipe sequence `%>%` – Andrew Mar 09 '20 at 12:33

1 Answers1

1

Since you didn't provide a MRE i had to create it myself:

df<- data.frame(id = 1:5,
                Prefix_1 = c(1, 2, 3, NA, 5),
                Prefix_2 = c(NA, 1, 2, 3, NA))

Solution, how to replace NA with fictional data:

df[, grepl("^Prefix_", names(df))][is.na(df[, grepl("^Prefix_", names(df))])] <- 0

df is now:

 id Prefix_1 Prefix_2
1  1        1        0
2  2        2        1
3  3        3        2
4  4        0        3
5  5        5        0

Just be aware that only because we can replace NAs with 0 doesn't mean we should. I assume you have an excellent reason why NAs should be 0 ;)

Edit:

Solution with dplyr:

df<- data.frame(id = 1:5,
                Prefix_1 = c(1, 2, 3, NA, 5),
                Prefix_2 = c(NA, 1, 2, 3, NA))


library(dplyr)   
df %>% 
  mutate_at(vars(matches("^Prefix")), coalesce,  0)

Or, using dplyr and tidyr::starts_with:

library(dplyr)   
library(tidyr)
df %>% 
  mutate_at(vars(starts_with("Prefix")), coalesce,  0)
dario
  • 6,415
  • 2
  • 12
  • 26
  • Hi Dario, i used df[, grepl("^Prefix_", names(df))][is.na(df[, grepl("^Prefix_", names(df))])] <- 0 ; and it worked ... thanks... :) – supratik ghosh Mar 09 '20 at 13:52