A dataframe:
mydf <- data.frame(
SOME_FIELD = 1:3,
ANOTHER_FIELD = letters[1:3]
)
I would like to replace all underscores in the field names with a space. Tried:
mydf %>% rename_all(str_replace_all('_', ' '))
Error in fix_replacement(replacement) :
argument "replacement" is missing, with no default
How can I change all names to use spaces instead of underscores?
CodePudding user response:
You may use -
library(dplyr)
library(stringr)
mydf %>% rename_all(~str_replace_all(., '_', ' '))
# SOME FIELD ANOTHER FIELD
#1 1 a
#2 2 b
#3 3 c
Since rename_all
has been replaced with rename_with
-
mydf %>% rename_with(~str_replace_all(., '_', ' '))
Or in base R -
names(mydf) <- gsub('_', ' ', names(mydf))
CodePudding user response:
We may use sub
in base R
names(mydf) <- sub("_", " " , names(mydf))
mydf
SOME FIELD ANOTHER FIELD
1 1 a
2 2 b
Or use chartr
library(dplyr)
mydf %>%
rename_with(~ chartr('_', " ", .), everything())
SOME FIELD ANOTHER FIELD
1 1 a
2 2 b
3 3 c