我如何连接(合并,组合)两个值? 例如,我有:

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

我的目标是将“tmp”中的两个值连接到一个字符串:

tmp_new = "GAD,AB"

哪个函数可以帮我做这个?


当前回答

另一种方法:

sprintf("%s you can add other static strings here %s",string1,string2)

它有时比paste()函数有用。%s表示将包含主观字符串的位置。

注意,这将在你试图构建路径时派上用场:

sprintf("/%s", paste("this", "is", "a", "path", sep="/"))

输出

/this/is/a/path

其他回答

> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"

我从谷歌中通过搜索R个串联字符串找到了这个:http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

你可以创建自己的操作符:

'%&%' <- function(x, y)paste0(x,y)
"new" %&% "operator"
[1] newoperator`

你也可以重新定义'and'(&)操作符:

'&' <- function(x, y)paste0(x,y)
"dirty" & "trick"
"dirtytrick"

混淆基线语法是丑陋的,但是使用paste()/paste0()也是如此,如果你只使用自己的代码,你可以(几乎总是)将逻辑&和操作符替换为*,并执行逻辑值的乘法,而不是使用逻辑'and '

另一种方法:

sprintf("%s you can add other static strings here %s",string1,string2)

它有时比paste()函数有用。%s表示将包含主观字符串的位置。

注意,这将在你试图构建路径时派上用场:

sprintf("/%s", paste("this", "is", "a", "path", sep="/"))

输出

/this/is/a/path

正如其他人所指出的,paste()是正确的方法。但是每次需要使用非默认分隔符时,都必须输入paste(str1, str2, str3, sep= "),这很烦人。

您可以非常容易地创建包装器函数,使工作变得更加简单。例如,如果你发现自己经常连接没有分隔符的字符串,你可以这样做:

p <- function(..., sep='') {
    paste(..., sep=sep, collapse=sep)
}

或者如果你经常想从一个向量连接字符串(比如PHP中的implode()):

implode <- function(..., sep='') {
     paste(..., collapse=sep)
}

允许你这样做:

p('a', 'b', 'c')
#[1] "abc"
vec <- c('a', 'b', 'c')
implode(vec)
#[1] "abc"
implode(vec, sep=', ')
#[1] "a, b, c"

此外,还有内置的paste0,它做的事情与我的implode相同,但不允许自定义分隔符。它比paste()稍微高效一些。

或者,如果你的目标是直接输出到文件或标准输出,你可以使用cat:

cat(s1, s2, sep=", ")