Function in R: use list argument as character string

I am writing a function that uses a list argument. As part of this function, I will convert the list to a data frame with stack(). Now, to my question, how can I rename the column of the resulting data frame (or any other, as necessary for the real function) with the name of the list that 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

}

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 the call stack_and_rename(fields) obviously returns a data frame with column values ​​and a “list”, although I would like to get “values” and “fields”. I have to make some link errors, but I just can't get a solution. Thank you

+4
source share
1 answer

deparse(substitute 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)

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"
+5

Source: https://habr.com/ru/post/1691586/


All Articles