Open In App

Remove Leading whitespaces from a String in R Language – trimws() Function

Last Updated : 23 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to remove whitespaces from a String in R Programming Language.

R – trimws() Function

trimws() function in R Language is used to trim the leading white spaces. It shrinks an object by removing outermost rows and columns with the same values.

Syntax: trimws(x)

Parameters: 

  • x: Object or character string

Example 1: Remove Leading and Trailing Whitespace 

R




# R program to illustrate
# Removing of leading whitespaces
 
# Create example character string
my_text <- "     . This is a trim     function     example "
 
# Apply trimws function in R
print(trimws(my_text))


Output: 

".  This is a trim       function      example"

Here in the above code, we have created a character string and have white spaces in it, So we have used the trimws() function to remove the white spaces.

Example 2: Remove whitespaces from a String in R

R




# R program to illustrate
# Removing of leading whitespaces
 
# Create example character string
my_text <- "     Geeks_For_Geeks     "
 
# Apply trimws function in R
print(trimws(my_text))


Output:

"Geeks_For_Geeks     "

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads