[R] assign value to multiple objects with a given ls pattern

Ivan Calandra ivan.calandra at uni-hamburg.de
Mon Feb 21 17:57:04 CET 2011


Hi,

This works for me:
pat <- ls(pattern="^a") ## I would anchor "a" to the beginning with "^" 
for safety!
for (i in seq_along(pat))assign(pat[i], value=99)

Or this with lapply:
lapply(pat, FUN=function(x) assign(x, value=99, envir=.GlobalEnv))

See ?assign

HTH,
Ivan

Le 2/21/2011 17:22, Nuno Prista a écrit :
> Dear R colleagues,
>
> This seems pretty straight forward but I have been banging my head on this for some time and can't seem to find a solution
>
> suppose I have something like
>
> a1<-1; a2<-2; a3<-3; a4<-4; b1<-3; b2<-4
> I would like to quickly assign to objects with a certain pattern, e.g., those in
>
> ls(pattern="a")
>
> a specific value, e.g., "99", without having to assign each object at a time.
>
> is there a way I can do this within a "for" cycle? I have tested several eval and parse statements but with no success.
>
> Regards,
>
> Nuno Prista
>
> ____________________________
> PhD student
> Instituto de Oceanografia
> Faculdade de Ciências da Universidade de Lisboa
> Campo Grande, Lisboa,
> 1749-016 Lisboa,
> Portugal
>
> ______________________________________________
> 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.
>

-- 
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Abt. Säugetiere
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de

**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/1525_8_1.php



More information about the R-help mailing list