R trimws() Function - Removing Whitespace Characters

R 语言实例R Language Examples

The R trimws() function is used to remove whitespace characters (spaces, tabs, newlines, etc.) at the beginning and end of strings.

In data cleaning, trimws() can remove extra spaces that were accidentally included in user input.

The syntax of the trimws() function is as follows:

trimws(x, which = c("both", "left", "right"))

Parameter description:

  • xInput character vector.

  • whichWhich side to remove whitespace from: "both" (both sides), "left" (left side), "right" (right side).

Example

text <- "  Hello EXAMPLE  "

# Remove whitespace on both sides
result1 <- trimws(text)
print(result1)

# Remove whitespace only on the left side
result2 <- trimws(text, which = "left")
print("Left only:")
print(result2)

# Remove whitespace only on the right side
result3 <- trimws(text, which = "right")
print("Right only:")
print(result3)

# Process a vector
names_with_spaces <- c(" Zhang San ", " Li Si", "Wang Wu ")
cleaned_names <- trimws(names_with_spaces)
print("Cleaned names:")
print(cleaned_names)

Executing the above code produces the following output:

[1] "Hello EXAMPLE"
[1] "只去左侧:"
[1] "Hello EXAMPLE  "
[1] "只去右侧:"
[1] "  Hello EXAMPLE"
[1] "清理后的名字:"
[1] "张三" "李四" "王五"

R 语言实例R Language Examples

Other Extensions