rlistassignment-operatorinversemultiple-assignment

R: Dismembering a list/referring to the current environment


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.


Solution

  • 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.