Reputation: 75
I have a dataset in R with several columns. Some of them contain qualitative values, whose first character is a blank space. I would like to know how I can remove only the blanks in front of the qualitative value. For example, " Living room" should be "Living room". I have thought about implementing the str_replace function and include the pattern that allows to do it, however, I need to perform this procedure in several columns of the dataset.
Any better idea?
str_replace(df$column, *pattern*)
Upvotes: 0
Views: 59
Reputation: 1154
You can use trims()
across multiple variables (i.e., columns) of your data frame using mutate()
and across()
from the dplyr
package. First, here's some toy data:
df <- data.frame(
id = c(1,2, 3),
var1 = c(" Living Room", " Kitchen", " Great Room"),
var2 = c(" Guest Room", " Master Bedrom", " Bathroom"),
var3 = c(" Office", " Laundry Room", " Casita")
)
df %>% glimpse()
Output:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> " Living Room", " Kitchen", " Great Room"
$ var2 <chr> " Guest Room", " Master Bedrom", " Bathroom"
$ var3 <chr> " Office", " Laundry Room", " Casita"
library(dplyr)
df <- df %>%
mutate(
across(starts_with("var"), trimws)
)
df %>% glimpse()
Output:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> "Living Room", "Kitchen", "Great Room"
$ var2 <chr> "Guest Room", "Master Bedrom", "Bathroom"
$ var3 <chr> "Office", "Laundry Room", "Casita"
Upvotes: 1