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!