library(stringr)
<- c("art", "introduction of the modern Art") x # reduce each string to a max of 10 characters, including ellipsisstr_trunc(x, width = 10)
Output:
[1] "art" "introdu..."
str_trunc()
is similar to str_pad()
, but truncates the strings to a fixed length specified by the width
argument. By default, the extra length beyond the width
value on the right side of the string will be truncated and replaced with ellipsis ...
.
library(stringr)
<- c("art", "introduction of the modern Art") x # reduce each string to a max of 10 characters, including ellipsisstr_trunc(x, width = 10)
Output:
[1] "art" "introdu..."
You can truncate the extra length from the left side, and use a different set of characters in replace of the ellipsis.
str_trunc(x, width = 10, side = "left", ellipsis = "**")
Output:
[1] "art" "**dern Art"
Not use ellipsis or special characters.
str_trunc(x, width = 10, side = "right", ellipsis = "")
Output:
[1] "art" "introducti"
If you want to ensure that all strings are the same length (often useful for print methods), consider combining str_pad()
and str_trunc()
.
# load the pipeline operatorlibrary(dplyr)
<- c("wine", "mozzarella", cuisine "grilled beef", "baked potato and onion")
%>% cuisine # truncate long strings to width 10 str_trunc(10, ellipsis = "") %>% # pad short strings to width 10 str_pad(10, side = "right", pad = "-")
Output:
[1] "wine------" "mozzarella" "grilled be" "baked pota"