[R] Using assign with mapply

Julio Sergio Santana juliosergio at gmail.com
Tue Dec 10 16:32:36 CET 2013


David Winsemius <dwinsemius <at> comcast.net> writes:

> So what happens if you try this:
> 
> mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(envir = .GlobalEnv)
> 

Yes, it works in certain situations, as well as the equivalent code:

     kkk <- data.frame(vars=c("var1", "var2", "var3"), 
                  vals=c(10, 20, 30), stringsAsFactors=F)

     mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(pos = 1))
     var1
    [1] 10

See, however, the following example

    : example <- function () {
        var1 <- 250
        kkk <- data.frame(vars=c("var1", "var2", "var3"), 
                      vals=c(10, 20, 30), stringsAsFactors=F)
        mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(pos = 1))
        print (var2)
        print (var1)
      }
 
      example()
     [1] 20
     [1] 250

My question is: how to get the combination of mapply and assign to affect 
the variables defined in the block where the construction is executed?

Maybe there is still something I don't understand.


Thanks,

  -Sergio.



More information about the R-help mailing list