Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate a vector? [duplicate]

I'm trying to produce a single variable which is a concatenation of two chars e.g to go from "p30s4" "p28s4" to "p30s4 p28s4". I've tried cat and paste as shown below. Both return empty variables. What am I doing wrong?

> blah = c("p30s4","p28s4") > blah [1] "p30s4" "p28s4"  > foo = cat(blah) p30s4 p28s4 > foo NULL  > foo = paste(cat(blah)) p30s4 p28s4 > foo character(0) 
like image 822
John Avatar asked May 02 '10 03:05

John


People also ask

How do you concatenate vectors?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.

What does it mean to concatenate a vector?

Description. The Vector Concatenate and Matrix Concatenate blocks concatenate the input signals to create a nonvirtual output signal whose elements reside in contiguous locations in memory. In the Simulink® library, these blocks are different configurations of the same block.

How do I remove duplicates in vector?

Using std::remove function A simple solution is to iterate the vector, and for each element, we delete all its duplicates from the vector if present. We can either write our own routine for this or use the std::remove algorithm that makes our code elegant.


2 Answers

Try using:

> paste(blah, collapse = "") [1] "p30s4p28s4" 

or if you want the space in between:

> paste(blah, collapse = " ") [1] "p30s4 p28s4" 
like image 138
shuttle87 Avatar answered Oct 01 '22 19:10

shuttle87


A alternative to the 'collapse' argument of paste(), is to use do.call() to pass each value in the vector as argument.

do.call(paste,as.list(blah)) 

The advantage is that this approach is generalizable to functions other than 'paste'.

like image 25
wkmor1 Avatar answered Oct 01 '22 20:10

wkmor1