Re: [R] Assigning variables using a loop

From: Nick Mosely <mosely_at_uw.edu>
Date: Sat, 23 Apr 2011 15:35:45 -0700

Thank you for your help. That works for me.

On Sat, Apr 23, 2011 at 1:53 PM, Joshua Wiley <jwiley.psych_at_gmail.com> wrote:
> Hi Nick,
>
> It is typically not a good idea to write functions that automatically
> assign variables to the global environment (makes it easy to overwrite
> something valuable without knowing you are overwriting it), but if
> that is really the best choice for your situation, I would do
> something like (inside your function):
>
> # note, if global assignment not needed, just return this
> mydata <- list(x = 1, y = 2, z = 3)
> lapply(names(mydata), function(x) {
>  assign(x, mydata[[x]], pos = .GlobalEnv)
> })
>
> HTH,
>
> Josh
>
> On Sat, Apr 23, 2011 at 10:51 AM, Nick Mosely <mosely_at_uw.edu> wrote:
>> Hello R-world,
>>
>> I have multiple variables that have been generated within a function.
>> I would like to assign them each to the Global Environment. I've tried
>> the following:
>>
>> x = 1
>> y = 2
>> z = 3
>> for (i in c(x,y,z)) {
>>  assign("i",i,pos=.GlobalEnv)
>> }
>> i
>> [1] 3
>>
>> Obviously, the problem is that the code is assigning numbers to the
>> the new variable i. I tried to get cute using paste:
>>
>>> x = 1
>>> y = 2
>>> z = 3
>>> for (i in c(x,y,z)) {
>> +   assign(paste(i),i,pos=.GlobalEnv)
>> + }
>>
>> But paste enters "1" when i is x, rather than the desired "x". Does
>> anyone know of a solution to this problem?
>>
>> Thanks,
>>
>> Nick
>>
>> ______________________________________________
>> R-help_at_r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> --
> Joshua Wiley
> Ph.D. Student, Health Psychology
> University of California, Los Angeles
> http://www.joshuawiley.com/
>



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun 24 Apr 2011 - 05:42:27 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 24 Apr 2011 - 05:50:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive