2

Within one of my functions, I need to change the name of a variable in a dataset. I created that new variable name and saved it in an object called name. When I rename the variable using the object name, R is making the name of the variable "name" instead of the contents of the object, name. How can I get it to use the object, name instead of the word "name"?

new_name <- paste("New","Name") 
#tidyverse approach library(dplyr) state_df <- as.data.frame(state.x77) new_data <- state_df %>% rename(name=Population) head(new_data) 

Base R approach

colnames(new_data)[colnames(new_data)=="Population"] <- name head(new_data) 

1 Answer 1

4

You can use {{new_name}}

new_name <- paste("New","Name") as.data.frame(state.x77) %>% rename({{new_name}}:=Population) %>% head() New Name Income Illiteracy Life Exp Murder HS Grad Frost Area Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708 Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432 Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417 Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945 California 21198 5114 1.1 71.71 10.3 62.6 20 156361 Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766 

Alternatively, you can do this

state = as.data.frame(state.x77) colnames(state)[which(colnames(state)=="Population")] <- new_name head(state) New Name Income Illiteracy Life Exp Murder HS Grad Frost Area Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708 Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432 Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417 Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945 California 21198 5114 1.1 71.71 10.3 62.6 20 156361 Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766 
Sign up to request clarification or add additional context in comments.

3 Comments

The brackets worked! Thanks so much. Is that a base R feature or a tidyverse feature?
checkout rlang.r-lib.org/reference/embrace-operator.html. By the way, your own base R approach above actually works fine, if you use state_df (i.e. colnames(state_df)[colnames(state_df)=="Population"] <- new_name)
Oh, shoot. I screwed that up when I was trying to create a reprex. Thanks for pointing that out!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.