Learning_and_xbox
Learning_and_xbox

Reputation: 63

How do you conditionally add a character string to certain values in a column?

I found that leading 0s had dropped from my data set at some point. Maybe someone had opened a CSV file and the leading 0s had fallen off or the data had been read in as an integer and the 0s had been removed. I'd been expecting all my ids to be 5 characters long and noticed an issue when some of them weren't.

TLDR: How do you conditionally add a string onto observations in a column?

Upvotes: 0

Views: 298

Answers (2)

Merijn van Tilborg
Merijn van Tilborg

Reputation: 5887

v <- c(1, 11, 111, 1111, 11111)

sprintf("%05d", v)

# [1] "00001" "00011" "00111" "01111" "11111"

Upvotes: 1

Learning_and_xbox
Learning_and_xbox

Reputation: 63

Thought I'd share how to do this in case anyone runs into similar issues. This is useful to add leading 0s back into a data frame where they may have been dropped (E.G. loaded in as an integer data type, someone opened a CSV file and the 0s dropped, for example). In this case, I expected all of my IDs to be 5 digits long, so corrected for the conditionally dropped 0s. This solution has an emphasis on the tidyverse.

dataset <-
  dataset %>%
  mutate(id = as.character(id)) %>%
  mutate(id = case_when(nchar(id) == 4 ~ paste("0", id, sep =""), 
                         nchar(id) == 5~ id))

Upvotes: 0

Related Questions