Reputation: 21282
I'd like to replace all underscores in a dataframes feature names with a space:
library(tidyverse)
names <- c("a_nice_day", "quick_brown_fox", "blah_ha_ha")
example_df <- data.frame(
x = 1:3,
y = LETTERS[1:3],
z = 4:6
)
names(example_df) <- names
Tried:
example_df %>% rename_all(replace = c("_" = " "))
Error: `.funs` must specify a renaming function
Also tried:
example_df %>% rename_all(funs(replace = c("_" = " ")))
Error: `nm` must be `NULL` or a character vector the same length as `x`
How can I replace all the underscores in the feature names with a space?
Upvotes: 7
Views: 9202
Reputation: 14764
What about:
example_df %>% select_all(funs(gsub("_", " ", .)))
Output:
a nice day quick brown fox blah ha ha
1 1 A 4
2 2 B 5
3 3 C 6
You could also use rename
, however in this case you'd need to call it in a different way:
example_df %>% rename_all(function(x) gsub("_", " ", x))
Or simply:
example_df %>% rename_all(~ gsub("_", " ", .))
Upvotes: 10
Reputation: 2945
With base R:
colnames(example_df) <- gsub("_", " ", colnames(example_df))
Upvotes: 5