Home > Enterprise >  How to return all elements in function-created list by their name?
How to return all elements in function-created list by their name?

Time:11-27

I have created the following example function:

my_function <- function(input_1, input_2){

a <- input_1*2
b <- input_2*3
c <- input_2*10

return(list(a = a, b = b, c = c))

}

How can I save all the elements of the resultant list to the working environment without doing so manually? To do it by brute force, I would just do:

func_list <- my_function(input_1 = 5, input_2 = 6)
a <- func_list$a
b <- func_list$b
c <- func_list$c

In the project I'm working on, I need to return a lot of objects into the environment (either the global environment or in a function), so doing so manually every time is not feasible. Is there a way to return all the items at once? Would it be possible, also, to return all objects created within the function itself (and not have to make a return list that specifies every object)?

CodePudding user response:

To save them as vectors directly in your enviroment you coud use the operator <<-

my_function <- function(input_1, input_2){
  
  a <<- input_1*2
  b <<- input_2*3
  d <<- input_2*10
  
}

my_function(input_1 = 5, input_2 = 6)

But be careful since this could be dangerous if not properly used, also c is already a function in R, so don't use as variable name!

CodePudding user response:

As the function is returning a named list, use list2env

list2env(my_function(input_1 = 5, input_2 = 6), .GlobalEnv)

-checking

> a
[1] 10
> b
[1] 18
> c
[1] 60

Or another option is to specify an environment

my_function <- function(input_1, input_2, env = parent.frame())
    {
env$a <- input_1*2
env$b <- input_2*3
env$c <- input_2*10


}

-testing

> rm(a, b, c)
> my_function(input_1 = 5, input_2 = 6)
> a
[1] 10
> b
[1] 18
> c
[1] 60
  • Related