开发者

Is there a way to paste together the elements of a vector in R without using a loop?

开发者 https://www.devze.com 2023-03-20 15:10 出处:网络
Say there\'s a vector x: x <- c(\"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:

Say there's a vector x:

x <- c("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)

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?


You just need to use the collapse argument:

paste(x,collapse="")


Just adding a tidyverse way to provide an alternative to using paste():

library(glue)
x <- c("a", " ", "b")
glue_collapse(x)
#> a b

Created on 2020-10-31 by the reprex package (v0.3.0)

0

精彩评论

暂无评论...
验证码 换一张
取 消