library(stringr)<- c("a", "bee") hive str_pad(hive, width = 5) # width of resulted string
Output:
[1] " a" " bee"
str_pad()
adds white space (or other characters) to a string so that it becomes a fixed length (or said width). By default, white space is added to the left side of the string. In the following example, 4 spaces are added before “a”, and 2 before “bee”, so that each padded string element is of length 5.
library(stringr)<- c("a", "bee") hive str_pad(hive, width = 5) # width of resulted string
Output:
[1] " a" " bee"
Here we pad with “-” at both sides of each string.
str_pad(hive, width = 5, side = "both", pad = "-")
Output:
[1] "--a--" "-bee-"
We can use vectorized arguments to pad string elements into different length and with different characters.
str_pad(hive, width = c(4, 6), side = "both", pad = c("-", "*"))
Output:
[1] "-a--" "*bee**"
If the original string element is longer than the specified width
value, the original string will remain the same; it will not be truncated.
str_pad(c(hive, "beeees"), width = 5, side = "both", pad = "-")
Output:
[1] "--a--" "-bee-" "beeees"