Menu

Creating sample data

Name <- c(“Abbey”, ”     Brian”, “Connie     “, ”     Dan iel     “)

Base R Method
We can use trimws() . The syntax is as follows

trimws(dataframe, which)

which  can take three values: ‘left’, ‘right’, or ‘both’.

Base – Removing Leading Whitespace Only

Base – Removing Trailing Whitespace Only

Base – Removing Both

Please notice that in all three examples, space between ‘Dan’ and ‘iel’ is not removed since the function is strictly only leading and trailing.

Stringr Method
In addition to Base R, we can also use str_trim()  from Stringr library, which essentially the same except changing which  to side .

Stringr – Removing Leading Whitespace Only

Stringr – Removing Trailing Whitespace Only

Stringr – Removing Both