如何使用apply in R将字符串粘贴到字符串向量的每个元素上?

时间:2021-08-16 21:29:21

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.

为此,我想将字符串“day”以类似的方式粘贴到向量的每个元素上。

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

2 个解决方案

#1


70  

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


9  

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

其他已经表明,由于粘贴是矢量化的,所以在本例中没有必要使用apply。

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):

但是,要回答您的问题:apply用于数组或data.frame。当您想在列表(或向量)上应用一个函数时,请使用lapply或sapply(简化结果的lapply的变体):

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

#1


70  

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


9  

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

其他已经表明,由于粘贴是矢量化的,所以在本例中没有必要使用apply。

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):

但是,要回答您的问题:apply用于数组或data.frame。当您想在列表(或向量)上应用一个函数时,请使用lapply或sapply(简化结果的lapply的变体):

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