Reputation: 4408
Background
I have a dataset, df. Whenever I try and rename the 'TanishaIsCool' column, I get an error: unexpected string constant. I wish to add spaces within my column name
TanishaIsCool Hello
hi hi
This is what I am doing:
df1 <- df %>% rename(Tanisha Is Cool = `TanishaIsCool` )
Desired output
Tanisha Is Cool Hello
hi hi
dput
structure(list(TanishaIsCool = structure(1L, .Label = "hi", class = "factor"),
Hello = structure(1L, .Label = "hi", class = "factor")), class = "data.frame", row.names = c(NA,
-1L))
Upvotes: 2
Views: 2814
Reputation: 61
Your attempt was nearly there, except missing the backquotes/backticks:
df1 %>% rename(`Tanisha Is Cool` = TanishaIsCool)
However, I believe you will find that most recommendations (and I agree completely after my own personal experience of struggling with one particular dataset...), state not to use spaces in your variable names, since you might find that when you have to reference these variables, you will have to always include the `` , which can get pretty cumbersome.
Just realised @thelatemail has answered exactly this in the comment!
Upvotes: 3
Reputation: 887981
We can use gsub
to capture the lower case letter (([a-z])
), then the upper case (([A-Z])
) and in the replacement, use the backreference of the captured groups (\\1,
\2`) and create space between them
colnames(df1) <- gsub("([a-z])([A-Z])", "\\1 \\2", colnames(df1))
df1
# Tanisha Is Cool Hello
#1 hi hi
With tidyverse
and option is
library(dplyr)
library(stringr)
library(magrittr)
df1 %<>%
rename_all(~ str_replace_all(., "([a-z])([A-Z])", "\\1 \\2"))
For selected columns, use rename_at
df1 %<>%
rename_at(1, ~ str_replace_all(., "([a-z])([A-Z])", "\\1 \\2"))
Another option is regex lookaround
gsub("(?<=[a-z])(?=[A-Z])", " ", names(df1), perl = TRUE)
#[1] "Tanisha Is Cool" "Hello"
If we need to update only selected column names, then use an index, hre it is the first column
names(df1)[1] <- gsub("(?<=[a-z])(?=[A-Z])", " ", names(df1)[1], perl = TRUE)
Upvotes: 1