web-dev-qa-db-ja.com

2つの文字列をどのように連結することができますか?

2つの値を連結(結合、結合)する方法たとえば、私は持っています:

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

私の目標は、 "tmp"の2つの値を1つの文字列に連結することです。

tmp_new = "GAD,AB"

どの機能がこれを実行できますか?

336
Hans
paste()

行く方法です。前のポスターが指摘したように、pasteは2つのことをすることができます。

値を1つの "文字列"に連結します。

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

お役に立てれば。

447
Rainer

help.search()は便利な関数です。

> help.search("concatenate")

paste()にあなたを導くでしょう。

77
rtelmore

最初のnon -paste()の答えについては、stringr::str_c()(そして次に下のtoString())を見てください。この質問ほど長くは出ていないので、それも存在することを言及するのは有益だと思います。

ご覧のとおり、使い方はとても簡単です。

tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"

そのドキュメントファイルの説明から、それはこの問題にうまく合っています。

Str_cがどのように機能するのかを理解するには、文字列の行列を構築していることを想像する必要があります。各入力引数は列を形成し、通常のリサイクル規則を使用して最長の引数の長さに拡張されます。 sep文字列は各列の間に挿入されます。 collapseがNULLの場合、各行は1つの文字列にまとめられます。 NULL以外の場合、その文字列は各行の末尾に挿入され、行列全体が単一の文字列に縮小されました。

加えられた4/13/2016 :それはあなたの望む出力と全く同じではない(余分なスペース)が、だれもそれを述べていない。 toString()は基本的にcollapse = ", "がハードコードされたpaste()のバージョンです。

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

他の人が指摘しているように、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()よりも少し効率的です。

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

R連結文字列 http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html を検索して、Googleからこれを見つけました。

29
Ville Salonen

あるいは、ファイルまたは標準出力に直接出力することが目的の場合は、catを使用できます。

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

独自の演算子を作成できます:

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

'and'(&)演算子を再定義することもできます:

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

ベースライン構文の混乱はsingいですが、paste()/paste0()を使用しているので、独自のコードでのみ作業する場合は、(ほとんどの場合)論理& and演算子を*に置き換えて論理値の乗算を行うことができます論理的な「and&」を使用する代わりに

18
Qbik

別の方法:

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
17
Suat Atan PhD

行列tmpを作成したとします。

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

単純ではなく、cbindを使用して行列を作成するのにはいくつかの理由があると思います。

tmp <- "GAD,AB"
14
neilfws

文字列が列で、結果が新しい列になる場合を考えます。

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 = ", ")) 
2
joel.wilson

別の非ペースト回答:

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

どこで

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

glueは、tidyverseの一部として開発された新しい関数、データクラス、およびパッケージです。それはpaste、sprintf、そして前の他の答えからの機能を兼ね備えています。

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

2019-03-06に Representxパッケージ (v0.2.1)によって作成されました。

はい、この質問の簡単な例ではやり過ぎですが、多くの状況で強力です。 ( https://glue.tidyverse.org/ /を参照)

以下のpasteを使用したwithと比較した簡単な例です。 glueコードは少し入力しやすく、少し読みやすくなっています。

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

2019-03-06に Representxパッケージ (v0.2.1)によって作成されました。

1
Arthur Yip