R Func Trimws
# R trimws() functions - Remove Whitespace
[ R Language Examples](#)
The R trimws() function is used to remove whitespace characters (spaces, tabs, newlines, etc.) from the beginning and end of strings.
In data cleaning, trimws() can remove extra spaces that users accidentally include in their input.
The syntax of the trimws() function is as follows:
trimws(x, which = c("both", "left", "right"))
**Parameter Description:**
* **x** Input string vector.
* **which** Which side of whitespace to remove: "both" (both sides), "left" (left side), "right" (right side).
## Example
text<-" Hello TUTORIAL "
# Remove whitespace from both sides
result1 <- trimws(text)
print(result1)
# Only remove whitespace from left side
result2 <- trimws(text, which="left")
print("Remove left only:")
print(result2)
# Only remove whitespace from right side
result3 <- trimws(text, which="right")
print("Remove right only:")
print(result3)
# Process vector
names_with_spaces <-c(" Zhang San ", " Li Si", "Wang Wu ")
cleaned_names <- trimws(names_with_spaces)
print("Cleaned names:")
print(cleaned_names)
Execute the above code, the output is:
"Hello TUTORIAL" "Remove left only:" "Hello TUTORIAL " "Remove right only:" " Hello TUTORIAL" "Cleaned names:" "Zhang San" "Li Si" "Wang Wu"
[ R Language Examples](#)
YouTip