有没有办法在不使用循环的情况下将 R 中的向量元素粘贴在一起? [英] Is there a way to paste together the elements of a vector in R without using a loop?

查看:78
本文介绍了有没有办法在不使用循环的情况下将 R 中的向量元素粘贴在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个向量 x:

x <- c("a", " ", "b")

我想快速将其转换为单个字符串a b".有没有办法在没有循环的情况下做到这一点?我知道通过循环我可以做到这一点:

and I want to quickly turn this into a single string "a b". Is there a way to do this without a loop? I know with a loop I could do this:

y <- ""
for (i in 1:3){
    paste(y, x[i], sep = "")
}

> y
[1] "a b"

但是我需要在很多很多次迭代中执行此操作,并且每次都必须循环并用新的替换原始内容将变得非常耗时.我一直希望能够做这样的事情:

but I will need to do this over many, many iterations, and having to loop over this and replace the original with the new each time would become very time consuming. I always want to be able to do something like this:

x <- paste(x)

好像 paste() 可以巧妙地划分向量本身的元素,但我知道它不能.有没有其他函数,或者更有创意的使用 paste() 的方法,可以有效地完成这个任务?

as if paste() could smartly divide up the elements of a vector itself, but I know it can't. Is there another function, or a more creative way to use paste(), which can accomplish this efficiently?

推荐答案

你只需要使用 collapse 参数:

You just need to use the collapse argument:

paste(x,collapse="")

这篇关于有没有办法在不使用循环的情况下将 R 中的向量元素粘贴在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆