62

我有一个字符串向量。

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

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

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

3 回答 3

113

不需要apply(),只需使用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> 
于 2011-08-08T15:51:29.527 回答
13

其他人已经表示,由于是矢量化的,因此在这种情况下paste无需使用。apply

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

sapply(d, paste, "day", sep="")
        Mon        Tues      Wednes       Thurs         Fri       Satur 
   "Monday"   "Tuesday" "Wednesday"  "Thursday"    "Friday"  "Saturday" 
        Sun 
   "Sunday" 
于 2011-08-08T15:52:27.130 回答
4

除了paste/之外,paste0还有多种方法可以将字符串添加到向量中的每个元素。

1)使用sprintf

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

2)glue

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

这里{d}被评估为 R 代码。as.character如果需要,可以将其包裹起来。

3)str_cstringr

stringr::str_c(d, "day")

其等价物是

4)stri_cstringi

stringi::stri_c(d, "day")

5)stringi还有stri_paste

stringi::stri_paste(d, "day")
于 2019-09-26T07:24:51.153 回答