I'm trying to fix some cells in a tibble. The column of my interest contains strings with white spaces and double white spaces at begin or end.
I saw these posts before asking
- Merge Multiple spaces to single space; remove trailing/leading spaces
- How to remove extra white space between words inside a character vector using?
- How to remove all whitespace from a string?
- How to trim leading and trailing whitespace in R?
This is a reproducible example of what I'm doing
library(dplyr)
mtcars2 = tbl_df(mtcars) %>%
mutate(name = rownames(mtcars)) %>%
mutate(name = gsub("^ *|(?<= ) | *$", "", name, perl = TRUE)) %>%
mutate(name = gsub("^\\s+|\\s+$", "", name)) %>%
mutate(name = iconv(name, from = "", to = "ASCII//TRANSLIT", sub = ""))
head(mtcars2, 3)
And the result is
# A tibble: 3 × 12
mpg cyl disp hp drat wt qsec vs am gear carb name
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Datsun 710
But in my dataset after doing that some double white spaces persist !!
Is there a more general command to remove white spaces at the end of string? Many thanks in advance !