Reputation: 1050
I need to replace NA with FALSE across multiple lists. I can do it in the most basic way. Here is what I have so far -
mydataframe$POBA<-replace_na(mydataframe$POBA,FALSE)
mydataframe$POBA2<-replace_na(mydataframe$POBA2,FALSE)
mydataframe$POBA3<-replace_na(mydataframe$POBA3,FALSE)
Is there a way to combine all three to reduce the code? Using a For Loop or referring to a range of columns?
Just started teaching myself R and I've tried multiple variations, but none that seem to work.
Upvotes: 1
Views: 45
Reputation: 887028
We can use mutate_at
library(dplyr)
mydataframe <- mydataframe %>%
mutate_at(vars(starts_with("POBA)), replace_na, FALSE)
In the devel version of dplyr
, across
can be used in mutate
mydataframe %>%
mutate(across(starts_with("POBA"), replace_na, FALSE))
Upvotes: 1
Reputation: 10340
You could use the apply family for that
lapply(mydataframe, replace_na, FALSE)
Note: This would alter all columns and will return a list object. This can easily be converted to a data.frame again with as.data.frame()
if you need that.
mydataframe <- data.frame(POBA = c(TRUE,TRUE,NA),
POBA2 = c(TRUE, NA, TRUE),
POBA3 = c(NA, TRUE, TRUE))
lapply(mydataframe, tidyr::replace_na, FALSE)
# $POBA
# [1] TRUE TRUE FALSE
#
# $POBA2
# [1] TRUE FALSE TRUE
#
# $POBA3
# [1] FALSE TRUE TRUE
Upvotes: 0