Skip to content
Prev 334609 / 398528 Next

Using assign with mapply

The take home message that you should be learning from your struggles
is to "Not Use The 'assign' Function!" and "Do Not Use Global
Variables Like This".

R has lists (and environments) that make working with objects that are
associated with each other much simpler and fits better with the
functional programming style of R.

For example you can create a list from your data frame quickly and
easily with code like:

mydata <- as.list(kkk$vals)
names(mydata) <- kkk$vars

or

mydata <- setNames( as.list(kkk$vals), kkk$vars )

then you will have you variables (with names) inside the list (mydata
in this example, but name it whatever you want)

This list can then be passed out of a function or otherwise used.

To access a specific variable by name you can do:

mydata$var1

or

mydata[['var2']]

or

with(mydata, var3)

but you can also do things like (and this is often a follow-up
question to questions like yours):

varname <- 'var3'
mydata[[ varname ]]

and you can also use lapply and sapply to do the same action on every
variable in your list:

sapply( mydata, function(x) x + 5 )

instead of having to loop through a bunch of global variables.

And if you want to save or delete these, now you just save or delete
the entire list rather than having to loop through the set of global
variables.

If you tell us more about how you want to use these variables we can
give more suggestions, but the main point is that in the long run you
will be happier learning to use lists (and possibly environments) in
place of trying to create and work with global variables like you
asked about.




On Mon, Dec 16, 2013 at 8:55 AM, Julio Sergio Santana
<juliosergio at gmail.com> wrote: