Erik Brole
Erik Brole

Reputation: 365

Is there any command to remove space in dataframe columns?

In a dataframe like this:

data.frame(id = c("google", "Amazon"), text1 = c("Lee  erke rle  "," Elrl fe"), text2 = c(" Text  e2  ","text Els "))

Is there any command which can remove the spaces which are not useful/extra and convert to lower case all columns expect the first one?

Example output:

data.frame(id = c("google", "Amazon"), text1 = c("lee erke rle","elrl fe"), text2 = c("text e2 ","text els"))

Upvotes: 0

Views: 339

Answers (1)

Vinícius Félix
Vinícius Félix

Reputation: 8826

Here a tidyverse approach:

df <-
  data.frame(
    id = c("google", "Amazon"),
    text1 = c("Lee  erke rle  "," Elrl fe"),
    text2 = c(" Text  e2  ","text Els ")
  )

library(dplyr)
library(stringr)


df %>% 
  mutate(across(
    .cols = starts_with("text"),
    .fns = ~str_to_lower(str_squish(.))
  ))

Output

      id        text1    text2
1 google lee erke rle  text e2
2 Amazon      elrl fe text els

Upvotes: 1

Related Questions