0

I am trying to write a function that can be used in the execution environment of a function that is the inverse operation to list, i.e., given a named list, it returns the named elements as named objects. This is what I have:

library(tidyverse)

unfold <- function(X){list2env(X, envir = rlang::current_env())}

l. <- list(A = 1, B = 2)

tst_unlist <- function(X){
  unfold(X)
  out <- as.list(rlang::current_env())
  out
}

tst_unlist(X = l.)

This returns:

$X
$X$A
[1] 1

$X$B
[1] 2

In other words, all there is in the environment is X, containing the list l..

Desired output:

$X
$X$A
[1] 1

$X$B
[1] 2


$A
[1] 1

$B
[1] 2

In other words, the I want the unfold function to assign the assigned the elements of list l. into the current (execution) environment of tst_unlist.

andrewH
  • 2,281
  • 2
  • 22
  • 32

1 Answers1

1

You don't want the current environment, your unfold function should be using the calling environment in order to create variables in the tst_unlist scope. So just do

unfold <- function(X){list2env(X, envir = rlang::caller_env())}

Using current_env() would just place those objects in the environment of the executing unfold function.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I actually tried that (and a bunch of less sensible things) . This causes a a huge number of things scroll by & off the top edge of the console very quickly. It looks like the caller environment is my global environment (which contains an unreasonable number of large objects).. This is true if _either_ the unfold environment or the environment captured by as.list() is set to caller_env(). It seems the caller of both unfold and as.list should be the execution environment for tst_unlist. Or the execution env of list2env & <-, respectively. But that still shouldn't be my global environment. – andrewH Apr 30 '19 at 01:23
  • The code of rlang::caller_env is as follows: function (n = 1) { parent.frame(n + 1) } – andrewH Apr 30 '19 at 01:26
  • @andrewH I tested this and it worked for me. Only the unfold function should use caller_env. The tst_unlist should continue to use current_env. – MrFlick Apr 30 '19 at 01:29
  • And now it is working for me too. Don't know why it wasn't before. Thanks! – andrewH Apr 30 '19 at 04:00