user3184906
user3184906

Reputation: 31

Converting numbers into strings

I need to transform a lot of numbers into strings. The difficult part for me is that all strings must be 4 letters long. For example "1" must be "0001" or "234" must be "0234". I think this is a simple question, but I could not find the answer. Thanks for your help!

Upvotes: 2

Views: 88

Answers (2)

nico
nico

Reputation: 51650

As an alternative to sprintf you can use formatC.

For example

> formatC(1:10, width=4, flag="0")
 [1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010"

Upvotes: 4

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193547

You can use sprintf:

> sprintf("%04d", 1)
[1] "0001"
> sprintf("%04d", c(1, 23, 123))
[1] "0001" "0023" "0123"

Upvotes: 4

Related Questions