[R] Using assign with mapply

David Winsemius dwinsemius at comcast.net
Sat Dec 7 01:11:25 CET 2013


On Dec 6, 2013, at 11:27 AM, Julio Sergio Santana wrote:

> 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)
> 
> If I do 
> 
>   : assign(kkk$vars[1], kkk$vals[1])
> 
> it works
> 
>   : var1
>   [1] 10
> 
> However, if I try with mapply this is what I get:
> 
>   : mapply(assign, kkk$vars, kkk$vals)
>   var1 var2 var3 
>     10   20   30 
>   : var2
>   Error: object 'var2' not found
> 
> Maybe I have not undestand how mapply and assign work. Do you have
> any comments?

I think you will find that the value returned from the mapply call was a three element list with the desired names and values  ... except you then gave that enclosing list no name and it will be garbage-collected. If you want to have 'assign' do its magic into the global environment, then you need to supply 'mapply' a MoreArgs argument on the other side of the ellipsis:

Usage:
mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,
       USE.NAMES = TRUE)

So what happens if you try this:

mapply(assign,  kkk$vars, kkk$vals, MoreArgs = list(envir = .GlobalEnv)

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list