"

Replacing NAs in a dataframe

Today’s #rstats “I wish I’d known this sooner” moment: tidyr::replace_na()
Author
Affiliation

Building Stories with Data

Published

November 11, 2022

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!

# Create the data
my_messy_data <- tibble(
  name = c("Alice", 
           "Bob", 
           "Cara"),
  age = c(25, 
          35, 
          NA),
  favourite_food = c("Apples", 
                     "Boeuf Bourguignon", 
                     NA))
# Replace the NAs with whatever you like...
my_messy_data %>% 
  tidyr::replace_na(list(
    age = "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/.