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)