HOWTO · R

R에서 문자열 연결

이 튜토리얼은 R에서 문자열을 연결하는 방법을 보여줍니다.

문자열을 연결하여 둘 이상의 문자열을 연결할 수 있습니다. R 언어에는 문자열을 연결하는 몇 가지 방법이 있습니다. 이 튜토리얼은 R에서 문자열을 연결하는 방법을 보여줍니다.

R에서 paste() 메서드를 사용하여 문자열 연결

paste()는 R에서 문자열을 연결하는 가장 일반적인 방법입니다. 하나의 필수 매개변수와 두 개의 선택적 매개변수를 사용합니다.

paste() 함수의 구문은 다음과 같습니다.

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

어디:

  1. 문자열은 연결할 문자열입니다.
  2. sep는 두 문자열 사이에 추가되는 구분 문자입니다. 공백이나 다른 문자가 될 수 있습니다.
  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)

위의 코드는 먼저 두 개의 문자열을 연결한 다음 두 개 이상의 문자열을 연결합니다.

출력:

[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