R trimws() Function - Removing Whitespace
The R trimws() function is used to remove leading and trailing whitespace (spaces, tabs, newlines, etc.).
In data cleaning, trimws() can remove extra spaces accidentally included in user input.
The syntax of the trimws() function is as follows:
trimws(x, which = c("both", "left", "right"))
Parameter Description:
-
x The input vector of strings.
-
which Which side to remove whitespace from: "both" (both sides), "left" (left side), "right" (right side).
Example
text
<-
" Hello RUNOOB "
Remove whitespace from both sides
result1
<-
trimws
(
text
)
(
result1
)
Remove only leading whitespace
result2
<-
trimws
(
text
,
which
=
"left"
)
(
"Left only:"
)
(
result2
)
Remove only trailing whitespace
result3
<-
trimws
(
text
,
which
=
"right"
)
(
"Right only:"
)
(
result3
)
Process a vector
names_with_spaces
<-
c
(
" Zhang San "
,
" Li Si"
,
"Wang Wu "
)
cleaned_names
<-
trimws
(
names_with_spaces
)
(
"Cleaned names:"
)
(
cleaned_names
)
The output of the code above is:
[1] "Hello RUNOOB"
[1] "只去左侧:"
[1] "Hello RUNOOB "
[1] "只去右侧:"
[1] " Hello RUNOOB"
[1] "清理后的名字:"
[1] "张三" "李四" "王五"
R Language Examples