我有一个字符串向量。
d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun")
为此,我想以与此类似的方式将字符串“day”粘贴到向量的每个元素上。
week <- apply(d, "day", paste, sep='')
不需要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>
其他人已经表示,由于是矢量化的,因此在这种情况下paste
无需使用。apply
但是,要回答您的问题: apply
用于数组或 data.frame。当您想在列表(或向量)上应用函数时,请使用lapply
or sapply
(它的变体lapply
简化了结果):
sapply(d, paste, "day", sep="")
Mon Tues Wednes Thurs Fri Satur
"Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"
Sun
"Sunday"
除了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_c
在stringr
stringr::str_c(d, "day")
其等价物是
4)stri_c
在stringi
stringi::stri_c(d, "day")
5)stringi
还有stri_paste
stringi::stri_paste(d, "day")