[R] Using assign with mapply

Julio Sergio Santana juliosergio at gmail.com
Mon Dec 16 16:55:52 CET 2013


Julio Sergio Santana <juliosergio <at> gmail.com> writes:

> 
> I have a data frame whose first colum contains the names of the variables 
> and whose second colum contains the values to assign to them:
> 
>    : kkk <- data.frame(vars=c("var1", "var2", "var3"), 
>                      vals=c(10, 20, 30), stringsAsFactors=F)
> 

For those interested in the problem this is how I solved the problem:


I want to have something similar to:
#
#   var1 <- 10
#   var2 <- 20
#   var3 <- 30

my first trial was:

   mapply(assign,  kkk$vars, kkk$vals)
## var1 var2 var3 
## 10   20   30 
#

This is, however, what I got:

   var1
## Error: object 'var1' not found

David Winsemius suggested me something similar to 


   mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(pos = 1))
# or:
   mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(envir = .GlobalEnv))

var1
## [1] 10

This almost works, but what if this construction is used inside a function?

   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

var1, which was defined inside the function, isn't modified

To fix this, I defined the function as follows: 

   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 = sys.frame(sys.nframe())))
     # sys.nframe() is the number of the frame created inside the function
     # and sys.frame() establishes it as the one assign uses to set values
     print (var2)
     print (var1)
   }

   example()
## [1] 20
## [1] 10

And the purpose is got

Thanks,

  -Sergio.



More information about the R-help mailing list