0

In R, I'm looking for a way to add a specific character to all values in a column of a data frame based on the number of characters. Put it simply: if cell has 4 characters, do nothing. If a cell has 3 characters, add a 0 in front of every cell value. Every cell value has either 3 or 4 characters.

id <- c(1000, 2000, 300, 400, 5000, 600)
df <- data.frame(id)


#Desired Result (df)
#id         
#1000         
#2000      
#0300
#0400
#5000
#0600
Silhouettes
  • 145
  • 1
  • 10
  • 1
    `sprintf('%04d', df$id)` – Ronak Shah May 25 '20 at 09:22
  • ```library(stringr)``` ```id <- str_pad(id, 4, pad = "0")``` Did the job. Thanks to [Richie Cotton](https://stackoverflow.com/users/134830/richie-cotton) in [How to add leading zero's?](https://stackoverflow.com/questions/5812493/how-to-add-leading-zeros) – Silhouettes May 25 '20 at 09:50

0 Answers0