我如何连接(合并,组合)两个值? 例如,我有:
tmp = cbind("GAD", "AB")
tmp
# [,1] [,2]
# [1,] "GAD" "AB"
我的目标是将“tmp”中的两个值连接到一个字符串:
tmp_new = "GAD,AB"
哪个函数可以帮我做这个?
我如何连接(合并,组合)两个值? 例如,我有:
tmp = cbind("GAD", "AB")
tmp
# [,1] [,2]
# [1,] "GAD" "AB"
我的目标是将“tmp”中的两个值连接到一个字符串:
tmp_new = "GAD,AB"
哪个函数可以帮我做这个?
当前回答
另一个非粘贴的答案:
x <- capture.output(cat(data, sep = ","))
x
[1] "GAD,AB"
在哪里
data <- c("GAD", "AB")
其他回答
另一个非粘贴的答案:
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)
对于第一个非paste()答案,我们可以查看stringr::str_c()(然后是下面的toString())。它的存在时间没有这个问题长,所以我认为提到它也存在是有用的。
如你所见,使用起来非常简单。
tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"
从它的文档文件描述来看,它很好地解决了这个问题。
为了理解str_c是如何工作的,您需要想象您正在构建一个字符串矩阵。每个输入参数组成一个列,并使用通常的回收规则扩展到最长参数的长度。sep字符串被插入到每一列之间。如果collapse为NULL,则每一行都被折叠成单个字符串。如果非null,则在每一行的末尾插入该字符串,整个矩阵将折叠为单个字符串。
2016年4月13日补充:它与您期望的输出不完全相同(额外的空间),但也没有人提到它。toString()基本上是一个带有collapse = ", "硬编码的paste()版本,所以你可以这样做
toString(tmp)
# [1] "GAD, AB"
或者,如果你的目标是直接输出到文件或标准输出,你可以使用cat:
cat(s1, s2, sep=", ")
考虑这样一种情况,字符串是列,结果应该是一个新列:
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 = ", "))