如何使用 R 中的 apply 将字符串粘贴到字符串向量的每个元素上?
我有一个字符串向量。
d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun")
为此,我想以与此类似的方式将字符串“day”粘贴到向量的每个元素上。
week <- apply(d, "day", paste, sep='')
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='')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不需要
apply()
,只需使用paste()
:No need for
apply()
, just usepaste()
:其他人已经指出,由于
paste
是矢量化的,因此在这种情况下不需要使用apply
。但是,回答您的问题:
apply
用于数组或 data.frame。当您想要对列表(或向量)应用函数时,请使用lapply
或sapply
(lapply
的变体,简化了结果):Other have already indicated that since
paste
is vectorised, there is no need to useapply
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 uselapply
orsapply
(a variant oflapply
that simplifies the results):除了
paste
/paste0
之外,我们还可以通过多种方式向向量中的每个元素添加字符串。1) 使用
sprintf
2)
glue
这里
{d}
被评估为 R 代码。如果需要,可以将其包装在as.character
中。3)
stringr
中的str_c
其等效项为
4)
stringi
中的stri_c
5)
stringi
> 还有stri_paste
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
2)
glue
Here
{d}
is evaluated as R code. This can be wrapped inas.character
if needed.3)
str_c
instringr
whose equivalent is
4)
stri_c
instringi
5)
stringi
also hasstri_paste