littleworth
littleworth

Reputation: 5169

How to pad strings in a vector under paste0() sequentially

I can do the following:

> paste0("cat.", 1:10, ".jpg")

which gives:

[1] "cat.1.jpg"  "cat.2.jpg"  "cat.3.jpg"  "cat.4.jpg"  "cat.5.jpg"  "cat.6.jpg"  "cat.7.jpg"  "cat.8.jpg" 
[9] "cat.9.jpg"  "cat.10.jpg"

How can I pad the paste0() to produce

[1] "cat.01.jpg"  "cat.02.jpg"  "cat.03.jpg"  "cat.04.jpg"  "cat.05.jpg"  "cat.06.jpg"  "cat.07.jpg"  "cat.08.jpg" 
[9] "cat.09.jpg"  "cat.10.jpg"

At the end of the day what I want to do is to have sequence until 1000

paste0("cat.", 1:1000, ".jpg")

To get string like cat.0001.jpg.

Upvotes: 0

Views: 312

Answers (2)

Japie
Japie

Reputation: 51

No need for additional dependencies. You can just use sprintf() from base R as below:

sprintf("cat.%04d.jpg", 1:1000)

Upvotes: 0

PKumar
PKumar

Reputation: 11128

You may try to use stringr's str_pad as below:

library(stringr)
paste0("cat.", str_pad(1:10,width=2,side="left", pad=0), ".jpg")

To make it scalable to 1000, you can choose to change the second parameter (width) of str_pad to 4.

?str_pad

Vectorised over string, width and pad.

Usage

str_pad(string, width, side = c("left", "right", "both"), pad = " ")

Output:

> paste0("cat.", str_pad(1:10,2,pad=0), ".jpg")
 [1] "cat.01.jpg" "cat.02.jpg" "cat.03.jpg"
 [4] "cat.04.jpg" "cat.05.jpg" "cat.06.jpg"
 [7] "cat.07.jpg" "cat.08.jpg" "cat.09.jpg"
[10] "cat.10.jpg"

you may also choose to use stringr::str_c instead of paste0

Upvotes: 3

Related Questions