Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
R Program to Trim Leading and Trailing Whitespaces
In this example, we will learn to trim leading and trailing whitespaces using the trimws() function in R.
Example 1: Remove Whitespaces in R
text1 <- " Programiz Pro "
# remove whitespaces using trimws()
print(trimws(text1))
Output
[1] "Programiz Pro"
In the above example, we have used the trimws() function to remove the leading and trailing whitespace. It doesn't remove whitespace that appears in the middle.
Example 2: Remove Leading Whitespaces in R
text1 <- " Programiz Pro "
# remove leading whitespaces using trimws()
print(trimws(text1, "l"))
Output
[1] "Programiz Pro "
In the above example, we have passed "l" inside the trimws() function to remove the leading whitespaces in the text1 string.
Example 3: Remove Trailing Whitespaces in R
text1 <- " Programiz Pro "
# remove trailing whitespaces using trimws()
print(trimws(text1, "r"))
Output
[1] " Programiz Pro"
In the above example, we have passed "r" inside the trimws() function to remove the trailing whitespaces in the text1 string.