How to paste a string on each element of a vector

2019-01-11 00:06发布

问题:

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

回答1:

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> 


回答2:

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" 


标签: r paste apply