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

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

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

tmp_new = "GAD,AB"

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


当前回答

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

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

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

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

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

其他回答

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

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

Help.search()是一个方便的函数,例如:

> help.search("concatenate")

将引导您粘贴()。

考虑这样一种情况,字符串是列,结果应该是一个新列:

df <- data.frame(a = letters[1:5], b = LETTERS[1:5], c = 1:5)

df$new_col <- do.call(paste, c(df[c("a", "b")], sep = ", ")) 
df
#  a b c new_col
#1 a A 1    a, A
#2 b B 2    b, B
#3 c C 3    c, C
#4 d D 4    d, D
#5 e E 5    e, E

如果需要粘贴所有列,可以跳过[c("a", "b")]子设置。

# you can also try str_c from stringr package as mentioned by other users too!
do.call(str_c, c(df[c("a", "b")], sep = ", ")) 

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

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

给定你创建的矩阵tmp:

paste(tmp[1,], collapse = ",")

我假设有一些原因,为什么你创建一个矩阵使用cbind,而不是简单地:

tmp <- "GAD,AB"