How to paste a string on each element of a vector of strings using apply in R?

Viewed 80476

I have a vector of strings.

d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun")

for which I want to paste the string "day" on each element of the vector in a way similar to this.

week <- apply(d, "day", paste, sep='')
3 Answers

Apart from paste/paste0 there are variety of ways in which we can add a string to every element in the vector.

1) Using sprintf

sprintf("%sday", d)
#[1] "Monday"    "Tuesday" "Wednesday" "Thursday"  "Friday"  "Saturday"  "Sunday" 

2) glue

glue::glue("{d}days")

Here {d} is evaluated as R code. This can be wrapped in as.character if needed.

3) str_c in stringr

stringr::str_c(d, "day")

whose equivalent is

4) stri_c in stringi

stringi::stri_c(d, "day")

5) stringi also has stri_paste

stringi::stri_paste(d, "day")
Related