How can I concatenate a vector? [duplicate]

Deadly 提交于 2019-12-03 04:46:00

问题


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)

回答1:


Try using:

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

or if you want the space in between:

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



回答2:


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




回答3:


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
}



回答4:


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.



来源:https://stackoverflow.com/questions/2752323/how-can-i-concatenate-a-vector

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