简体   繁体   中英

Using an object to rename a variable in R

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM