How can I concatenate a vector? [duplicate]

蹲街弑〆低调 提交于 2019-12-02 17:57:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!