2

I am using the below code to replace N/As in multiple columns (but not all columns) in an R dataframe , however I am devoting a line of code for each column. I wondered if there is a cleaner and tidyier way of doing this. See code below

csvDF$Carechildinneed[is.na(csvDF$Carechildprotectionplan)] <- ""
csvDF$Carechildprotectionplan[is.na(csvDF$Carechildprotectionplan)] <- ""
csvDF$Careeligiblechild[is.na(csvDF$Careeligiblechild)] <- ""
csvDF$Careorder[is.na(csvDF$Careorder)] <- ""
csvDF$Carerelevantchild[is.na(csvDF$Carerelevantchild)] <- ""
csvDF$Careremandtolaa[is.na(csvDF$Careremandtolaa)] <- ""
csvDF$Careremandtoyda[is.na(csvDF$Careremandtoyda)] <- ""
csvDF$Caresiblings[is.na(csvDF$Caresiblings)] <- ""
csvDF$Carevoluntary[is.na(csvDF$Carevoluntary)] <- ""
Nick Read
  • 53
  • 2

3 Answers3

4

We can use replace to replace the NA elements to '' after looping across the columns

library(dplyr)
mtcars %>%
     mutate(across(cols, ~ replace(., is.na(.), "")))
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Try something like:

library(dplyr)
mtcars %>% mutate(across(cols, ~replace_na(.,"")))

If you save the columns you wish to modify in the vector cols.

As @Ben mentioned in the comments, you can use the tidyervse tidyselect functions such as starts_with("Care"), for example.

df %>% mutate(across(starts_with("Care", ~replace_na(.,"")))

The rest can be found here.

user438383
  • 5,716
  • 8
  • 28
  • 43
2

If you want to replace NA values in the 'Care' columns in base R, you can do -

cols <- grep('Care', names(csvDF))
csvDF[cols][is.na(csvDF[cols])] <- ''
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213