views:

282

answers:

3

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)
+11  A: 

Try using:

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

or if you want the space in between:

> paste(blah, collapse = " ")
[1] "p30s4 p28s4"
shuttle87
+5  A: 

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'.

wkmor1
A: 

The answers to this question are great, and much simpler than mine - so I have since adopted the use of 'collapse'.

However, to promote the idea that when in doubt, you can write your own function, I present my previous, less elegant solution:

  vecpaste <- function (x) {
     y <- x[1]
     if (length(x) > 1) {
         for (i in 2:length(x)) {
             history
             y <- paste(y, x[i], sep = "")
         }
     }
     #y <- paste(y, "'", sep = "")
     y
 }

vecpaste(blah)

you can also add quotes and commas, or just about anything - this is the original version that I wrote:

vecpaste <- function (x) {
y <- paste("'", x[1], sep = "")
if (length(x) > 1) {
    for (i in 2:length(x)) {
        history
        y <- paste(y, x[i], sep = "")
    }
}
y <- paste(y, "'", sep = "")
y
}
David