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

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

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

tmp_new = "GAD,AB"

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


当前回答

paste()

才是正确的选择。正如之前的海报所指出的,粘贴可以做两件事:

将值串联成一个“字符串”,例如:

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

其中参数sep指定在参数之间用于连接的字符, 或者折叠字符向量

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

其中参数collapse指定要折叠的vector元素之间使用的字符。

你甚至可以将两者结合起来:

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

其他回答

另一个非粘贴的答案:

x <- capture.output(cat(data, sep = ","))
x
[1] "GAD,AB"

在哪里

 data <- c("GAD", "AB")

Glue是作为tidyverse的一部分开发的一个新函数、数据类和包,具有许多扩展功能。它结合了paste、sprintf和前面其他答案的特性。

tmp <- tibble::tibble(firststring = "GAD", secondstring = "AB")
(tmp_new <- glue::glue_data(tmp, "{firststring},{secondstring}"))
#> GAD,AB

由reprex包于2019-03-06创建(v0.2.1)

是的,对于这个问题中的简单例子来说,它有点过头了,但在许多情况下都很强大。(参见https://glue.tidyverse.org/)

快速的例子比较粘贴与下面。胶水代码更容易输入,看起来也更容易阅读。

tmp <- tibble::tibble(firststring = c("GAD", "GAD2", "GAD3"), secondstring = c("AB1", "AB2", "AB3"))
(tmp_new <- glue::glue_data(tmp, "{firststring} and {secondstring} went to the park for a walk. {firststring} forgot his keys."))
#> GAD and AB1 went to the park for a walk. GAD forgot his keys.
#> GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys.
#> GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys.
(with(tmp, paste(firststring, "and", secondstring, "went to the park for a walk.", firststring, "forgot his keys.")))
#> [1] "GAD and AB1 went to the park for a walk. GAD forgot his keys."  
#> [2] "GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys."
#> [3] "GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys."

由reprex包于2019-03-06创建(v0.2.1)

给定你创建的矩阵tmp:

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

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

tmp <- "GAD,AB"
paste()

才是正确的选择。正如之前的海报所指出的,粘贴可以做两件事:

将值串联成一个“字符串”,例如:

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

其中参数sep指定在参数之间用于连接的字符, 或者折叠字符向量

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

其中参数collapse指定要折叠的vector元素之间使用的字符。

你甚至可以将两者结合起来:

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

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

> help.search("concatenate")

将引导您粘贴()。