3

I am writing a function that uses a list argument. Within this function, I am converting the list into a data frame using stack(). Now, my question is, how can I rename the column of the resulting data frame (or of any other, as would be needed for the real function) with the name of the list which I use in the function argument?

My function :

stack_and_rename <- function(list) {

stacked_list <- stack(list)
names(stacked_list)[names(stacked_list)=='ind'] <- 'list' 
stacked_list

}

A dummy list:

fields <- list(A = c(2:4, 12:16, 24:28, 36:40, 48:49), 
           B = c(6:10, 18:22, 30:34, 42:46))

But calling stack_and_rename(fields) obviously returns a data frame with the columns 'values' and 'list', although I would like to get 'values' and 'fields'. I must be making some referencing errors, but I just can't get the solution. Thanks!

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • 1
    This is really just [the wide-to-long question](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) again, e.g. `library(tidyr); fields %>% as.data.frame() %>% gather(fields)` – alistaire Jan 01 '18 at 17:44
  • @alistaire : I am sorry, but I don't see how the wide to long question is related to my question. Could you please explain? – tjebo Jan 02 '18 at 19:59

1 Answers1

5

We can use deparse(substitute from base R

stack_and_rename <- function(list) {
  nm1 <- deparse(substitute(list))
  stacked_list <- stack(list)
  names(stacked_list)[names(stacked_list)=='ind'] <- nm1
  stacked_list

}

stack_and_rename(fields)

Or with dplyr

library(dplyr)
stack_and_rename <- function(list) {
   nm1 <- quo_name(enquo(list))
   stacked_list <- stack(list)
   stacked_list %>%
       rename_at(vars('ind'), funs(paste0(nm1)))
       #or
       #rename(!! nm1 := ind)


}


stack_and_rename(fields) %>% 
          names
#[1] "values" "fields"
akrun
  • 874,273
  • 37
  • 540
  • 662