Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 545
Max Avatar asked Jul 14 '11 19:07

Max


People also ask

How do I paste elements into a vector in R?

You can use the paste() and paste0() functions in R to concatenate elements of a vector into a single string. The paste() function concatenates strings using a space as the default separator. The paste0() function concatenates strings using no space as the default separator.

What does Paste () do in R?

paste() method in R programming is used to concatenate the two string values by separating with delimiters.

What is a vector element in R?

Vector is a basic data structure in R. It contains element of the same type. The data types can be logical, integer, double, character, complex or raw. A vector's type can be checked with the typeof() function. Another important property of a vector is its length.


2 Answers

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)

like image 40
Ashirwad Avatar answered Sep 23 '22 11:09

Ashirwad


You just need to use the collapse argument:

paste(x,collapse="") 
like image 125
joran Avatar answered Sep 21 '22 11:09

joran