Reputation: 711
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
Upvotes: 6
Views: 5129
Reputation: 389335
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+", ""))
Upvotes: 8
Reputation: 522797
Why not just use sub
:
names(mpg) <- gsub("\\s+", "", names(mpg))
Upvotes: 6