Search code examples
renvironmentassign

How to access functions from a list in assign?


Assume I defined

methods <- list(hurz.default = function (vehicles, mission) {
    vehicles_r <- vehicles
    return(vehicles_r)}, 
  hurz.a = function (vehicles, mission) {
    vehicles_r <- vehicles[1, ]
    return(vehicles_r)})

now, this is working

i <- 1
assign(names(methods[i]), methods[[i]])

but this does not:

lapply(c(1:length(methods)), function(i) {
        assign(names(methods[i]), methods[[i]])
})

I could not find the answer using Hadley. Any thoughts?

(The idea came from here but I guess this is something else.)


Solution

  • We can specify the env

    lapply(seq_along(methods), function(i) {
           assign(names(methods)[i], methods[[i]], env = .GlobalEnv)
     })   
    
    
    hurz.default
    #function (vehicles, mission) {
    #    vehicles_r <- vehicles
    #    return(vehicles_r)}
    
    hurz.a
    #function (vehicles, mission) {
    #    vehicles_r <- vehicles[1, ]
    #    return(vehicles_r)}
    

    With a list, another option is list2env

    list2env(methods, .GlobalEnv)