开发者

How can I concatenate a vector? [duplicate]

开发者 https://www.devze.com 2022-12-29 01:30 出处:网络
This question already has answers here: Concatenate a vector of strings/character (8 answers) 开发者_如何学Go
This question already has answers here: Concatenate a vector of strings/character (8 answers) 开发者_如何学Go Closed 6 years ago.

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)


Try using:

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

or if you want the space in between:

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


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


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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消