The trimws() function can be used to remove leading and trailing whitespace in R DataFrame:
(1) To remove leading and trailing whitespace under a single column:
df$column_name <- trimws(df$column_name)
(2) To remove leading and trailing whitespace across the entire DataFrame:
df[] <- lapply(df, trimws)
Example 1: Remove Whitespace under a Single Column
To remove leading and trailing whitespace under the “product” column:
# Create a sample DataFrame df <- data.frame(product = c(" computer ", " monitor", "keyboard ", "printer", "tablet"), price = c(1200, 400, 100, 200, 300), brand = c("AAA", "BBB", "CCC", "DDD", "EEE") ) # Before trimming print("Before trimming:") print(df) # Trim whitespace under the product column df$product <- trimws(df$product) # After trimming print("After trimming:") print(df)
The result:
Before trimming:
product price brand
1 computer 1200 AAA
2 monitor 400 BBB
3 keyboard 100 CCC
4 printer 200 DDD
5 tablet 300 EEE
After trimming:
product price brand
1 computer 1200 AAA
2 monitor 400 BBB
3 keyboard 100 CCC
4 printer 200 DDD
5 tablet 300 EEE
Example 2: Remove Whitespace across the Entire DataFrame
To remove leading and trailing whitespace across the entire DataFrame in R:
# Create a sample DataFrame df <- data.frame(product = c(" computer ", " monitor", "keyboard ", "printer", "tablet"), price = c(1200, 400, 100, 200, 300), brand = c(" AAA ", "BBB ", "CCC ", "DDD", "EEE") ) # Before trimming print("Before trimming:") print(df) # Apply trimws() across the entire DataFrame df[] <- lapply(df, trimws) # After trimming print("After trimming:") print(df)
The result:
Before trimming:
product price brand
1 computer 1200 AAA
2 monitor 400 BBB
3 keyboard 100 CCC
4 printer 200 DDD
5 tablet 300 EEE
After trimming:
product price brand
1 computer 1200 AAA
2 monitor 400 BBB
3 keyboard 100 CCC
4 printer 200 DDD
5 tablet 300 EEE