HOWTO · R

R で文字列を連結する

このチュートリアルでは、R で文字列を連結する方法を示します。

連結文字列を使用して 2つ以上の文字列を結合できます。 R 言語には、文字列を連結する方法がいくつかあります。 このチュートリアルでは、R で文字列を連結する方法を示します。

R で paste() メソッドを使用して文字列を連結する

paste() は、R で文字列を連結する最も一般的な方法です。1つの必須パラメーターと 2つのオプション パラメーターを使用します。

paste() 関数の構文は次のとおりです。

paste(Strings, sep="", collapse=NULL)

どこ:

  1. Strings は連結したい文字列です。
  2. sep は、2つの文字列の間に追加される区切り文字です。 スペースまたはその他の文字を使用できます。
  3. collapse は区切り文字として使用するオプションの文字です。

いくつかの例を試してみましょう。

paste() を使用して文字列を連結する

単純な連結とは、セパレーターや折りたたみがないことを意味します。 paste() のデフォルトのセパレーターはスペースです。

例:

String1 = 'Hello'
String2 = 'World!'
String3 = 'This'
String4 = 'is'
String5 = 'Delftstack.com'

Result1 = paste(String1, String2)
print (Result1)

Result2 = paste(String1, String2, String3, String4, String5)
print (Result2)

上記のコードは、最初に 2つの文字列を連結し、次に 3つ以上の文字列を連結します。

出力:

[1] "Hello World!"

[1] "Hello World! This is Delftstack.com"

paste()sep を使用して文字列を連結する

sep は区切りを意味します。 以下の例は、区切り記号を使用した場合と使用しない場合の連結を示しています。

例:

String1 = 'Hello'
String2 = 'World!'
String3 = 'This'
String4 = 'is'
String5 = 'Delftstack.com'

# without any separator
Result1 = paste(String1, String2, String3, String4, String5, sep="")
print (Result1)

# with space separator
Result2 = paste(String1, String2, String3, String4, String5, sep=" ")
print (Result2)

# with a symbol separator
Result3 = paste(String1, String2, String3, String4, String5, sep=",")
print (Result3)

このコードは、区切り文字なしで文字列を連結し、スペースとコンマの区切り文字を使用して文字列を連結します。

出力:

[1] "HelloWorld!ThisisDelftstack.com"

[1] "Hello World! This is Delftstack.com"

[1] "Hello,World!,This,is,Delftstack.com"

collapsepaste() を使用して文字列を連結する

collapse を使用するには、最初に文字列のベクトルを作成し、それを collapse のパラメーターとして paste() メソッドに渡す必要があります。

例:

String1 <- 'Hello'
String2 <- 'World!'
String3 <- 'This'
String4 <- 'is'
String5 <- 'Delftstack.com'

String_Vec <- cbind(String1, String2, String3, String4, String5) # combined vector.
Result1 <- paste(String1, String2, String3, String4, String5, sep ="")
print(Result1)

Result2 <- paste(String_Vec, collapse = ":")
print(Result2)

上記のコードは、最初に文字列のベクトルを作成し、それを collapse セパレーターと共に paste() 関数に渡します。

出力:

[1] "HelloWorld!ThisisDelftstack.com"

[1] "Hello:World!:This:is:Delftstack.com"

R で cat() メソッドを使用して文字列を連結する

cat()paste() メソッドと同様に機能します。 文字列とセパレーターをパラメーターとして渡します。

例:

String1 <- 'Hello'
String2 <- 'World!'
String3 <- 'This'
String4 <- 'is'
String5 <- 'Delftstack.com'

Result1 <- cat(String1, String2, String3, String4, String5, sep =" ")

上記のコードは、同様に文字列を連結します。

出力:

Hello World! This is Delftstack.com

cat() を使用して連結結果をファイルに保存する

cat() は、連結結果をファイルに保存することもできます。

例:

String1 <- 'Hello'
String2 <- 'World!'
String3 <- 'This'
String4 <- 'is'
String5 <- 'Delftstack.com'

cat(String1, String2, String3, String4, String5, sep = '\n', file = 'temp.csv')
readLines('temp.csv')

上記のコードは、結果を CSV ファイルに保存します。

出力:

[1] "Hello"          "World!"         "This"           "is"             "Delftstack.com"

CSV