简体   繁体   中英

Changing column names within a function

When writing a function, how do I get the new name for baseline to change depending on what the name of my dataset is? With this function the column names become dataset_baseline and dataset_adverse instead of for example Inflation_baseline and Inflation_adverse.

renaming <- function(dataset) {
dataset <- dataset %>%
  rename(dataset_baseline = baseline, dataset_adverse = adverse)
return(dataset)
}

Try this :

renaming <- function(dataset,columns) {
  call = as.list(match.call())
  dataset.name <- toString(call$dataset)
  dataset %>% rename_at(columns,funs(paste0(dataset.name,.)))
}
dataset <- renaming(dataset,c("baseline","adverse"))

NOTE : You should not try to assign dataset from within your function : it won't work because the 'dataset' there would refer to a local variable of your function.

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