[R] looping over a string

Greg Snow Greg.Snow at imail.org
Thu Jan 22 22:28:36 CET 2009


Ah, I missed that.  You can get the value from the string by using paste to create the name of the variable (as you already did), then use the 'get' function to get its value (the other direction of assign).  But I would still suggest trying to use lists, then you can just use mylist[[ i ]] or mylist[[ names[i] ]] to grab the value or mylist[[ i ]] <- something  to assign.  Or even better, newlist <- lapply( oldlist, function ) and avoid the explicit loop altogether (then if you want to use the individual variables by name, just use with or within).

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r_lover at web.de [mailto:r_lover at web.de]
> Sent: Thursday, January 22, 2009 1:27 PM
> To: Greg Snow; r-help at R-project.org
> Subject: Re: [R] looping over a string
> 
> Greg Snow schrieb:
> > I don't see right off why the one works and the other doesn't, but
> this looks like one of those cases that would be better done using a
> list rather than global variables.
> >
> > Instead of assigning the variables in the global workspace, create a
> list and assign them there.  Then you can use lapply instead of a loop
> and you avoid the potential pitfalls associated with globals.
> >
> > Hope this helps,
> >
> >
> Greg,
> 
> thanks for the answer. The difference is, that in the first case I
> assign a value to a "string", but afterwards I want to read the value
> of
> the "string".
> 
> Trying to get it with lists.
> 
> Cheers,
> Thomas




More information about the R-help mailing list