如何连接两个字符串?

发布于 2024-12-01 15:48:59 字数 222 浏览 1 评论 0原文

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

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

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

tmp_new = "GAD,AB"

哪个函数可以为我执行此操作?

How can I concatenate (merge, combine) two values?
For example I have:

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

My goal is to concatenate the two values in "tmp" to one string:

tmp_new = "GAD,AB"

Which function can do this for me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

猫烠⑼条掵仅有一顆心 2024-12-08 15:48:59
paste()

是要走的路。正如前面的海报所指出的,粘贴可以做两件事:

将值连接成一个“字符串”,例如

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

,参数 sep 指定要连接的参数之间要使用的字符,
或折叠字符向量

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

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

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

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

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

concatenate values into one "string", e.g.

> 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"
坠似风落 2024-12-08 15:48:59

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

> help.search("concatenate")

将引导您到paste()

help.search() is a handy function, e.g.

> help.search("concatenate")

will lead you to paste().

酷遇一生 2024-12-08 15:48:59

对于第一个非 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() 基本上是 paste() 的一个版本,其中 collapse = ", " 是硬编码的,所以你可以这样做

toString(tmp)
# [1] "GAD, AB"

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"
所谓喜欢 2024-12-08 15:48:59

正如其他人指出的那样,paste() 是正确的选择。但每次您需要非默认分隔符时都必须输入 paste(str1, str2, str3, sep='') ,这可能会很烦人。

您可以非常轻松地创建包装函数,使生活变得更加简单。例如,如果您发现自己经常连接不带分隔符的字符串,您可以这样做:

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

或者如果您经常想要连接来自向量的字符串(例如 PHP 中的 implode()):

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

允许您这样做this:

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() 稍微高效一些。

As others have pointed out, paste() is the way to go. But it can get annoying to have to type paste(str1, str2, str3, sep='') everytime you want the non-default separator.

You can very easily create wrapper functions that make life much simpler. For instance, if you find yourself concatenating strings with no separator really often, you can do:

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

or if you often want to join strings from a vector (like implode() from PHP):

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

Allows you do do this:

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

Also, there is the built-in paste0, which does the same thing as my implode, but without allowing custom separators. It's slightly more efficient than paste().

海风掠过北极光 2024-12-08 15:48:59
> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"

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

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

I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

独﹏钓一江月 2024-12-08 15:48:59

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

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

Alternatively, if your objective is to output directly to a file or stdout, you can use cat:

cat(s1, s2, sep=", ")
爱格式化 2024-12-08 15:48:59

另一种方式:

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

Another way:

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

It sometimes useful than paste() function. %s denotes the place where the subjective strings will be included.

Note that this will come in handy as you try to build a path:

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

output

/this/is/a/path
半世晨晓 2024-12-08 15:48:59

您可以创建自己的运算符:

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

您还可以重新定义“and”(&)运算符:

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

弄乱基线语法很丑陋,但使用 paste()/paste0() 也是如此code> 如果您只使用自己的代码,您可以(几乎总是)替换逻辑 & and 运算符与 * 进行逻辑值相乘,而不是使用逻辑“and &”

You can create you own operator :

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

You can also redefine 'and' (&) operator :

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

messing with baseline syntax is ugly, but so is using paste()/paste0() if you work only with your own code you can (almost always) replace logical & and operator with * and do multiplication of logical values instead of using logical 'and &'

懒猫 2024-12-08 15:48:59

给定您创建的矩阵 tmp:

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

我认为您使用 cbind 创建矩阵是有某种原因的,而不是简单地:

tmp <- "GAD,AB"

Given the matrix, tmp, that you created:

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

I assume there is some reason why you're creating a matrix using cbind, as opposed to simply:

tmp <- "GAD,AB"
冷血 2024-12-08 15:48:59

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

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

reprex 包 (v0.2.1) 于 2019 年 3 月 6 日创建

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

粘贴 与下面的 withglue 代码更容易输入,看起来也更容易阅读。

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 包 (v0.2.1) 创建于 2019 年 3 月 6 日

glue is a new function, data class, and package that has been developed as part of the tidyverse, with a lot of extended functionality. It combines features from paste, sprintf, and the previous other answers.

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

Created on 2019-03-06 by the reprex package (v0.2.1)

Yes, it's overkill for the simple example in this question, but powerful for many situations. (see https://glue.tidyverse.org/)

Quick example compared to paste with with below. The glue code was a bit easier to type and looks a bit easier to read.

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."

Created on 2019-03-06 by the reprex package (v0.2.1)

余生再见 2024-12-08 15:48:59

考虑字符串是列且结果应该是新列的情况:

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 = ", ")) 

Consider the case where the strings are columns and the result should be a new column:

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

Optionally, skip the [c("a", "b")] subsetting if all columns needs to be pasted.

# 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 = ", ")) 
旧人 2024-12-08 15:48:59

另一个非粘贴答案:

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

在哪里

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

Another non-paste answer:

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

Where

 data <- c("GAD", "AB")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文