How to get output with the same prefix than parameter function

Viewed 22

I want to get the input parameter of a function to create an output with the same prefix in the global env

fun_mtcars <- function(name_ref,...){
  df <- name_ref %>% 
    select(mpg,...) 
  .GlobalEnv$selec_name_ref <- df
}

fun_mtcars(mtcars,disp)

In global env a new data frame was created with the name "selec_name_ref " but I want a name "selec_mtcars"

I can do selec_mtcars <- fun_mtcars(mtcars,disp)
but I have a lot of function to execute

1 Answers

We may extract the object name as a string with deparse/substitute and use that in paste to create new object and assign to .GlobalEnv with [[ instead of $

fun_mtcars <- function(name_ref,...){
name_ref_str <- deparse(substitute(name_ref))
  df <- name_ref %>% 
    select(mpg,...) 
  .GlobalEnv[[paste0("select_", name_ref_str)]] <- df
}

-checking

fun_mtcars(mtcars,disp)
> head(select_mtcars)
                   mpg disp
Mazda RX4         21.0  160
Mazda RX4 Wag     21.0  160
Datsun 710        22.8  108
Hornet 4 Drive    21.4  258
Hornet Sportabout 18.7  360
Valiant           18.1  225
Related