65

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='')
joran
  • 169,992
  • 32
  • 429
  • 468
pedrosaurio
  • 4,708
  • 11
  • 39
  • 53

3 Answers3

118

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> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
14

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" 
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 1
    @pedrosaurio I have to point out that if you use `sapply` for this specific problem it would be hugely inefficient. Use the already vectorised form of `paste`, as @DirkEddelbuettel suggested. – Andrie Aug 08 '11 at 16:40
  • @DirkEddelbuettel Thanks, I was at first a bit confused for which answer I should tick as the good one. As Andrie's answer was the 'real' answer I thought that it should be selected as the good one but if it is a wrong method and it will create confusion for future reference I'll then change it. Thanks again – pedrosaurio Aug 09 '11 at 09:16
7

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")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213