Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I remove whitespace from all column names with dplyr?

Tags:

r

dplyr

Multiple column names of a CSV have whitespace in them. I'd like to remove the whitespace from these column names with a single dplyr command.

I've tried:

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_if(everything(), contains(" "), str_replace_all(" ", ""))

I'd expect to produce the original mpg dataframe, with the whitespaces that I inserted in the second line removed, but I get an error:

Error: Empty pattern not supported
like image 611
JohnDoeVsJoeSchmoe Avatar asked Jan 27 '23 06:01

JohnDoeVsJoeSchmoe


1 Answers

As @camille metions you can use rename_all

library(tidyverse)

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_all(~str_replace_all(., "\\s+", ""))

Or rename_at with everything()

mpg %>%
  rename("tr ans" = trans, "mo del" = model) %>%
  rename_at(vars(everything()), ~str_replace_all(., "\\s+", ""))
like image 58
Ronak Shah Avatar answered Jan 30 '23 09:01

Ronak Shah