Basil
Basil

Reputation: 1004

Replace NA using a vector of column names

I have a data frame with columns containing NAs which I replace using replace_na. The problem is these column names can change in the future so I would like to put these column names in a vector and then use the vector in the replace_na function. I don't want to change the entire data frame in one go, just specified columns. When I try this as below, the code runs but it doesn't change the data frame. Can anyone suggest any edits to the code?

library(tidyverse)
col1<-c(9,NA,25,26,NA,51)
col2<-c(9,5,25,26,NA,51)
col3<-c(NA,3,25,26,NA,51)
col4<-c(9,1,NA,26,NA,51)

data<-data.frame(col1,col2,col3,col4, stringsAsFactors = FALSE)

columns<-c(col1,col2)

data<-data%>%
  replace_na(list(columns=0))


Upvotes: 1

Views: 1118

Answers (3)

Anoushiravan R
Anoushiravan R

Reputation: 21908

Another option would be using coalesce inside map_at:

  • at argument in map_at can be a character vector of column names that you would like to modify
  • We then use coalesce function to specify the replacement of NAs
library(dplyr)
library(purrr)

data %>%
  map_at(c("col1","col2"), ~ coalesce(.x, 0)) %>%
  bind_cols()

# A tibble: 6 x 4
   col1  col2  col3  col4
  <dbl> <dbl> <dbl> <dbl>
1     9     9    NA     9
2     0     5     3     1
3    25    25    25    NA
4    26    26    26    26
5     0     0    NA    NA
6    51    51    51    51

Upvotes: 2

ktiu
ktiu

Reputation: 2626

A dplyr option:

columns <- c("col1" ,"col2")

dplyr::mutate(data, across(columns, replace_na, 0))

Returns:

  col1 col2 col3 col4
1    9    9   NA    9
2    0    5    3    1
3   25   25   25   NA
4   26   26   26   26
5    0    0   NA   NA
6   51   51   51   51

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388797

columns value should be string, you can then use is.na as -

columns<-c("col1","col2")

data[columns][is.na(data[columns])] <- 0
data

#  col1 col2 col3 col4
#1    9    9   NA    9
#2    0    5    3    1
#3   25   25   25   NA
#4   26   26   26   26
#5    0    0   NA   NA
#6   51   51   51   51

Or using tidyverse -

library(dplyr)
library(tidyr)

data <- data %>% mutate(across(all_of(columns), replace_na, 0))

Upvotes: 1

Related Questions