65

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?

Max
  • 805
  • 1
  • 6
  • 9

2 Answers2

129

You just need to use the collapse argument:

paste(x,collapse="")
joran
  • 169,992
  • 32
  • 429
  • 468
  • Thank you! I kept thinking there should be something called "collapse" involved in this, but I couldn't find any documentation on it. – Max Jul 14 '11 at 19:35
  • 5
    It's right there in `?paste`! ;) If you're ever confused about a function type `?function` in the console to access the help files. – joran Jul 14 '11 at 20:01
  • 1
    Yeah guess it didn't occur to me that it'd be an argument of paste. Just when you think you know a function...:P – Max Jul 14 '11 at 20:17
  • 2
    R help files are remarkably helpful, even if it isn't an argument of the function you might just find the function you are looking for:) – Sacha Epskamp Jul 14 '11 at 20:22
  • You can use ```paste(str_pad(l,width=7,side="left"), collapse = "")``` – Saurabh Jan 24 '20 at 18:33
7

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)

Ashirwad
  • 1,890
  • 1
  • 12
  • 14