0

I am very new to R and am having a hard time figuring out 1) how to get my data frame to show up in this thing, 2) how to add leading _0s of varying lengths to subject IDs. I have data that looks something like this

id = c(1, 2, 3, 11, 12, 13, 110, 120, 130)
sex = c(1, 2, 2, 1, 2, 1, 1, 2, 2)
age = c(12, 13, 10, 9, 14, 12, 10, 9, 11)
df = data.frame(id, sex, age)
df

I would like to add leading _0s so that each of the IDs are 3 numbers long. For example, 1 becomes _001, 11 becomes _011 and _110 stays as is.

Any suggestions?? And thanks for your patience...

Jess G
  • 188
  • 9

2 Answers2

3

stringr library has ya covered...

library(stringr)
> str_pad("1234", width=10, pad="0")
[1] "0000001234"
cory
  • 6,529
  • 3
  • 21
  • 41
2

The sprintf function in base R can be used for this:

> x <- c(1, 23, 456)
> sprintf("%03d", x)
[1] "001" "023" "456"
Greg Snow
  • 48,497
  • 6
  • 83
  • 110