<- c("mango", "peach", "lemon") fruit
library(stringr)# Repeat 2 times for each string element.str_dup(fruit, times = 2)
Output:
[1] "mangomango" "peachpeach" "lemonlemon"
str_dup()
makes duplicated copies for each element of a string vector. It changes the length of each string element, but not the length of the vector.
<- c("mango", "peach", "lemon") fruit
library(stringr)# Repeat 2 times for each string element.str_dup(fruit, times = 2)
Output:
[1] "mangomango" "peachpeach" "lemonlemon"
# Duplicate 0, 1, and 3 times, respectively, for the 1st, 2nd and 3rd string.str_dup(fruit, times = c(0, 1, 3))
Output:
[1] "" "peach" "lemonlemonlemon"
# Duplicate "na" 0 to 3 times, and combine with "ba".str_c("ba", str_dup("na", 0:3))
Output:
[1] "ba" "bana" "banana" "bananana"
In comparison, the base R function rep()
also creates replicates. However, it reserves the length of each element, and changes the length of the vector.
rep(fruit, times = 2)
Output:
[1] "mango" "peach" "lemon" "mango" "peach" "lemon"
rep(fruit, each = 2)
Output:
[1] "mango" "mango" "peach" "peach" "lemon" "lemon"