To trim a string in R, you can use the trimws()
function.
In this example,
" Hello World "
to the variable str1
.trimws()
function on str1
to remove leading and trailing whitespace characters.str1 <- " Hello World "
trimmedStr1 <- trimws(str1)
cat('Trimmed string is: ', trimmedStr1, '\n')
Trimmed string is: Hello World
In this example,
" apple"
to the variable str2
.trimws()
function with the which
parameter set to left
to remove leading whitespace characters.str2 <- " apple"
trimmedStr2 <- trimws(str2, which = 'left')
cat('Trimmed string is: ', trimmedStr2, '\n')
Trimmed string is: apple
In this example,
"banana "
to the variable str3
.trimws()
function with the which
parameter set to right
to remove trailing whitespace characters.str3 <- "banana "
trimmedStr3 <- trimws(str3, which = 'right')
cat('Trimmed string is: ', trimmedStr3, '\n')
Trimmed string is: banana
In this tutorial, we learned How to Trim a String in R language with well detailed examples.