# Create the data
<- tibble(
my_messy_data name = c("Alice",
"Bob",
"Cara"),
age = c(25,
35,
NA),
favourite_food = c("Apples",
"Boeuf Bourguignon",
NA))
Replacing NAs in a dataframe
Today’s #rstats “I wish I’d known this sooner” moment:
tidyr::replace_na()
Today’s #rstats “I wish I’d known this sooner” moment: tidyr::replace_na()
The list argument allows you to replace NAs in different columns with different things all in one go 🥳
Health warnings: - Beware of class changes - Use caution when replacing NAs!
# Replace the NAs with whatever you like...
%>%
my_messy_data ::replace_na(list(
tidyrage = "It is rude to ask",
favourite_food = "I like all food!")
)
# But watch out for class changes!
# (Age is now character)
# A tibble: 3 x 3
name age favourite_food <chr> <chr> <chr>
1 Alice 25 Apples
2 Bob 35 Boeuf Bourguignon
3 Cara It is rude to ask I like all food!
Reuse
Citation
For attribution, please cite this work as:
Thompson, Cara. 2022. “Replacing NAs in a Dataframe.”
November 11, 2022. https://www.cararthompson.com/posts/2022-11-11-todays-rstats-i-wish-id/.