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
1 |
trimws(Name, which = "left") |
1 2 |
> trimws(Name, which = "left") [1] "Abbey" "Brian" "Connie " "Dan iel " |
Base – Removing Trailing Whitespace Only
1 |
trimws(Name, which = "right") |
1 2 |
> trimws(Name, which = "right") [1] "Abbey" " Brian" "Connie" " Dan iel" |
Base – Removing Both
1 |
trimws(Name, which = "both") |
1 2 |
> trimws(Name, which = "both") [1] "Abbey" "Brian" "Connie" "Dan iel" |
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
1 |
str_trim(Name, side = "left") |
1 2 |
> str_trim(Name, side = "left") [1] "Abbey" "Brian" "Connie " "Dan iel " |
Stringr – Removing Trailing Whitespace Only
1 |
str_trim(Name, side = "right") |
1 2 |
> str_trim(Name, side = "right") [1] "Abbey" " Brian" "Connie" " Dan iel" |
Stringr – Removing Both
1 |
str_trim(Name, side = "both") |
1 2 |
> str_trim(Name, side = "both") [1] "Abbey" "Brian" "Connie" "Dan iel" |