How to replace NA w...
Notifications
Clear all

How to replace NA with 0 using starts with

RSS

(@anamika)
Noble Member
Joined: 2 years ago
Posts: 1381
11/05/2021 10:36 am

I am trying to replace NA values with 0 for a specific set of columns in my tibble. All the columns start with the same prefix. So, I want to know if there is a concise way to make use of the starts_with() function from the dplyr package that would allow me to do this.

I have tried replace_na() function from the tidyr package to no avail. Below is the code.

library(tidyverse)tibble1<-tibble(id=c(10,20,30),col_a=c(1,NA,4),col_b=c(NA,99,100),col_c=c("d","e",NA))replace_na(tbl1,list(starts_with("num_")=0)))

Quote
(@ganesh)
Noble Member
Joined: 2 years ago
Posts: 1362
11/05/2021 10:37 am

Well I could suggest various options such as mutate_at with if_else(or case_when). This works when you want to replace all the NA values in the columns with 0.

mutate_at(tibble1,vars(starts_with("col_")),funs(if_else(is.na(.),0,.)))# A tibble: 3 x 4id col_a col_b col_c<dbl><dbl><dbl><chr>11010d220099e3304100

Note: starts_with and other select helpers returnan integer vector giving the position of the matched variables.


ReplyQuote
Share:
Baidu