R에서 문자열 벡터를 연결하는 방법(예제 포함)


R에서 다음 방법 중 하나를 사용하여 문자열 벡터를 연결할 수 있습니다.

방법 1: Base R에서 Paste() 사용

 paste(vector_of_strings, collapse=' ')

방법 2: stringi 패키지의 stri_paste() 사용

 library (stringi)

stri_paste(vector_of_strings, collapse=' ')

두 방법 모두 동일한 결과를 생성하지만 특히 매우 큰 벡터로 작업하는 경우 stri_paste() 방법이 더 빠릅니다.

다음 예에서는 각 방법을 실제로 사용하는 방법을 보여줍니다.

예 1: Base R에서 Paste()를 사용하여 문자열 벡터 연결

다음 코드는 R 기본 붙여넣기() 함수를 사용하여 문자열 벡터를 연결하는 방법을 보여줍니다.

 #create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings
paste(vector_of_strings, collapse=' ')

[1] "This is a vector of strings"

축소 인수는 각 문자열 사이에 배치할 구분 기호를 지정합니다.

위의 예에서는 공백을 사용했습니다. 그러나 하이픈과 같은 구분 기호를 사용할 수 있습니다.

 #create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings using dash as delimiter
paste(vector_of_strings, collapse='-')

[1] “This-is-a-vector-of-strings”

각 문자열을 사이에 공백 없이 연결하려면 구분 기호를 전혀 사용하지 않아도 됩니다.

 #create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings using no delimiter
paste(vector_of_strings, collapse='')

[1] “Thisisavectorofstrings”

예제 2: stringi 패키지의 str_paste()를 사용하여 문자열 벡터 연결

다음 코드는 R의 stringi 패키지에 있는 stri_paste() 함수를 사용하여 문자열 벡터를 연결하는 방법을 보여줍니다.

 library (stringi)

#create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings
stri_paste(vector_of_strings, collapse=' ')

[1] "This is a vector of strings"

이는 기본 R Paste() 함수와 동일한 결과를 생성합니다.

유일한 차이점은 이 방법이 더 빠르다는 것입니다.

작업 중인 문자열 벡터의 크기에 따라 속도 차이가 중요할 수도 있고 중요하지 않을 수도 있습니다.

추가 리소스

다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

R에서 벡터를 문자열로 변환하는 방법
R에서 문자열을 소문자로 변환하는 방법
R에서 부분 문자열 일치를 수행하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다