R의 문자열에서 공백을 제거하는 방법(예제 3개)
다음 방법을 사용하여 R의 문자열에서 공백을 제거할 수 있습니다.
방법 1: gsub()를 사용하여 모든 공백 제거
updated_string <- gsub(" ", "", my_string)
방법 2: str_replace_all()을 사용하여 모든 공백 제거
library (stringr)
updated_string <- str_replace_all(my_string, " ", "")
방법 3: str_trim()을 사용하여 선행 및 후행 공백 제거
library (stringr) #remove all trailing whitespace updated_string <- str_trim(my_string, " right ") #remove all leading whitespace updated_string <- str_trim(my_string, " left ")
다음 예에서는 각 방법을 실제로 사용하는 방법을 보여줍니다.
예 1: gsub()를 사용하여 모든 공백 제거
다음 코드는 R의 gsub() 함수를 사용하여 주어진 문자열에서 모든 공백을 제거하는 방법을 보여줍니다.
#create string
my_string <- "Check out this cool string"
#remove all whitespace from string
updated_string <- gsub(" ", "", my_string)
#view updated string
updated_string
[1] "Checkoutthiscoolstring"
문자열에서 모든 공백이 제거되었습니다.
예제 2: str_replace_all()을 사용하여 모든 공백 제거
다음 코드는 R에서 stringr 패키지의 str_replace_all() 함수를 사용하여 주어진 문자열에서 모든 공백을 제거하는 방법을 보여줍니다.
library (stringr)
#create string
my_string <- "Check out this cool string"
#remove all whitespace from string
updated_string <- str_replace_all(my_string, " ", "")
#view updated string
updated_string
[1] "Checkoutthiscoolstring"
문자열에서 모든 공백이 제거되었습니다.
예제 3: str_trim()을 사용하여 선행 및 후행 공백 제거
다음 코드는 R에서 stringr 패키지의 str_trim() 함수를 사용하여 주어진 문자열에서 모든 선행 공백을 제거하는 방법을 보여줍니다.
library (stringr)
#create string with leading whitespace
my_string <- "Check out this cool string"
#remove all leading whitespace from string
updated_string <- str_trim(my_string, " left ")
#view updated string
updated_string
[1] “Check out this cool string”
모든 선행 공백이 제거되었습니다.
다음 코드는 str_trim() 함수를 사용하여 주어진 문자열에서 모든 후행 공백을 제거하는 방법을 보여줍니다.
library (stringr)
#create string with trailing whitespace
my_string <- "Check out this cool string "
#remove all trailing whitespace from string
updated_string <- str_trim(my_string, " right ")
#view updated string
updated_string
[1] “Check out this cool string”
모든 후행 공백이 제거되었습니다.
추가 리소스
다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
R의 문자열에서 문자 위치를 찾는 방법
R에서 문자열을 연결하는 방법
R에서 벡터를 문자열로 변환하는 방법
R에서 문자를 요소로 변환하는 방법