38

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)
zx8754
  • 52,746
  • 12
  • 114
  • 209
John
  • 5,139
  • 19
  • 57
  • 62
  • you're concatenating a vector, might want to change the question, but the answer is right nonetheless – Dan May 02 '10 at 03:55

4 Answers4

68

Try using:

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

or if you want the space in between:

> paste(blah, collapse = " ")
[1] "p30s4 p28s4"
shuttle87
  • 15,466
  • 11
  • 77
  • 106
12

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
  • 7,226
  • 3
  • 31
  • 23
2

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 LeBauer
  • 31,011
  • 31
  • 115
  • 189
1

The problem with your use of cat above is that cat(x) writes x to output, not to a variable. If you wanted to write to a string, you could do:

capture.output(cat(blah))

which as the name implies, captures the output in a string to return the desired result. However, this is not the preferred method, just an explanation by way of an alternate solution.

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134