1

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)
}
CAJ
  • 67
  • 5
  • 4
    Why do you want a function to achieve this? – nghauran Oct 03 '18 at 14:21
  • I'm assuming `dplyr::rename` because you're using `%>%`, but there is also `plyr::rename`. In questions (and answers), it is important to be explicit about non-base R packages needed for the question. – r2evans Oct 03 '18 at 14:27
  • 1
    This would be fairly easy if your data frame is in a `list` (and easy to do this to all the data frames in a list all at once), but is more difficult for a data frame floating around your environment. – Gregor Thomas Oct 03 '18 at 14:27
  • I have 15 datasets with the same column names, Country, Year, Baseline and Adverse, and I want to join them together. The data is the same for Country and Year but different for Baseline and Adverse, so I would like a dataset with all the variables included but need to rename them for that purpose – CAJ Oct 03 '18 at 14:27
  • 1
    Consider @Gregor's comment to use a named list to manage your many datasets and not independent objects requiring many `assign`, `get`, `eval(parse(...))` and other backdoor object references. – Parfait Oct 03 '18 at 14:28
  • 1
    Ah, 15 datasets with the same structure should certainly be in a list. I think an easier workflow would be (a) put the data frames in a list, (b) since you're already using `dplyr`, use `bind_rows` to stack them vertically with an automatically added ID column, (c) use `tidyr::spread` or `reshape2::dcast` to convert it into wide format. If you make a small reproducible example (with say, 2 data frames with 2-3 rows each) we can answer the full question. – Gregor Thomas Oct 03 '18 at 14:29
  • I was about to provide an answer highlighting the problem of using `deparse(substitute(dataset))` in this function, but the use of a [`list`-of-frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) seems a lot more useful here. – r2evans Oct 03 '18 at 14:31

1 Answers1

1

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.

Nicolas2
  • 2,170
  • 1
  • 6
  • 15