How can 2 strings be concatenated?

How can I merge/combine two value in R? For example I have:

tmp = cbind("GAD", "AB")
tmp
#      [,1]  [,2]
# [1,] "GAD" "AB"

My goal is to get tmp as one string

tmp_new = "GAD,AB"

Which Function can do this for me?


paste()

is the way to go. As the previous posters pointed out, paste can do two things:

concatenate values into one "string", eg

> paste("Hello", "world", sep=" ")
[1] "Hello world"

where the argument sep specifies the character(s) to be used between the arguments to concatenate, or collapse character vectors

> x <- c("Hello", "World")
> x
[1] "Hello" "World"
> paste(x, collapse="--")
[1] "Hello--World"

where the argument collapse specifies the character(s) to be used between the elements of the vector to be collapsed.

You can even combine both:

> paste(x, "and some more", sep="|-|", collapse="--")
[1] "Hello|-|and some more--World|-|and some more"

Hope this helps.


help.search() is a handy function, eg

> help.search("concatenate")

will lead you to paste() .


For the first non- paste() answer, we can look at stringr::str_c() (and then toString() below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.

Very simple to use, as you can see.

tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"

From its documentation file description, it fits this problem nicely.

To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.

Added 4/13/2016 : It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString() is basically a version of paste() with collapse = ", " hard-coded, so you can do

toString(tmp)
# [1] "GAD, AB"
链接地址: http://www.djcxy.com/p/24860.html

上一篇: 将列表中的项目连接到字符串

下一篇: 2个字符串如何连接?