Add leading characters to a string. This function is useful for ensuring, say, files get sorted in a particular order. For example, on some operating systems a file name "file 1" would come first, then "file 10", then "file 11", "file 12", etc., then "file 2", "file 21", and so on. Using prefix
, you can add one or more leading zeros so that file names are as "file 01", "file 02", "file 03", and so on... and they will sort that way.
Usage
prefix(x, len, pad = "0")
Arguments
- x
Character or character vector to which to add a prefix.
- len
The total number of characters desired for each string. If a string is already this length or longer then nothing will be prefixed to that string.
- pad
Character. Symbol to prefix to each string.
Value
Character or character vector.
Examples
prefix(1:5, len=2)
#> [1] "01" "02" "03" "04" "05"
prefix(1:5, len=5)
#> [1] "00001" "00002" "00003" "00004" "00005"
prefix(1:5, len=3, pad='!')
#> [1] "!!1" "!!2" "!!3" "!!4" "!!5"