Trim Whitespace of all Character Columns

mutate_all_trimws(
  data,
  which = c("both", "left", "right"),
  whitespace = "[ \t\r\n]"
)

Arguments

data

A dataframe or tibble.

which

a character string specifying whether to remove both leading and trailing whitespace (default), or only leading ("left") or trailing ("right"). Can be abbreviated.

whitespace

a string specifying a regular expression to match (one character of) “white space”, see Details for alternatives to the default.

See also

Examples

library(tidyverse) test_data <- tibble(A = sample(c(NA_integer_, 1:3), size = 10, replace = TRUE), B = sample(c(NA_integer_, 4:6), size = 10, replace = TRUE), C = sample(c(" apple ", "banana ", " orange", NA_character_), size = 10, replace = TRUE)) # Mutate all to character mutate_all_char(test_data)
#> # A tibble: 10 x 3 #> A B C #> <chr> <chr> <chr> #> 1 NA 5 " apple " #> 2 3 4 " orange" #> 3 1 4 "banana " #> 4 2 4 " orange" #> 5 NA 5 NA #> 6 NA 4 " orange" #> 7 3 NA "banana " #> 8 1 4 NA #> 9 2 5 "banana " #> 10 1 4 NA
# Trim whitespace at all character cols mutate_all_trimws(test_data, which = "both")
#> Error: Problem with `mutate()` input `C`. #> x unused argument (whitespace = whitespace) #> Input `C` is `(structure(function (..., .x = ..1, .y = ..2, . = ..1) ...`.
mutate_all_trimws(test_data, which = "left")
#> Error: Problem with `mutate()` input `C`. #> x unused argument (whitespace = whitespace) #> Input `C` is `(structure(function (..., .x = ..1, .y = ..2, . = ..1) ...`.
mutate_all_trimws(test_data, which = "right")
#> Error: Problem with `mutate()` input `C`. #> x unused argument (whitespace = whitespace) #> Input `C` is `(structure(function (..., .x = ..1, .y = ..2, . = ..1) ...`.