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

RPasteApply

R Problem Overview


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='')

R Solutions


Solution 1 - R

No need for apply(), just use paste():

R> d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun")
R> week <- paste(d, "day", sep="")
R> week
[1] "Monday"    "Tuesday"   "Wednesday" "Thursday"  
[4] "Friday"    "Saturday"  "Sunday"   
R> 

Solution 2 - R

Other have already indicated that since paste is vectorised, there is no need to use apply in this case.

However, to answer your question: apply is used for an array or data.frame. When you want to apply a function over a list (or a vector) then use lapply or sapply (a variant of lapply that simplifies the results):

sapply(d, paste, "day", sep="")
        Mon        Tues      Wednes       Thurs         Fri       Satur 
   "Monday"   "Tuesday" "Wednesday"  "Thursday"    "Friday"  "Saturday" 
        Sun 
   "Sunday" 

Solution 3 - R

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.

  1. str_c in stringr

    stringr::str_c(d, "day")

whose equivalent is

  1. stri_c in stringi

    stringi::stri_c(d, "day")

  2. stringi also has stri_paste

    stringi::stri_paste(d, "day")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpedrosaurioView Question on Stackoverflow
Solution 1 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 2 - RAndrieView Answer on Stackoverflow
Solution 3 - RRonak ShahView Answer on Stackoverflow