[R] Using changing names in loop in R

Liviu Andronic landronimirc at gmail.com
Sat Nov 6 20:23:59 CET 2010


On Sat, Nov 6, 2010 at 5:22 PM, Tuatara <franziskabroell at gmail.com> wrote:
>
> Hello everybody,
>
> I have usually solved this problem by repeating lines of codes instead of a
> loop, but it's such a waste of time, I thought I should really learn how to
> do it with loops:
>

Would the following construct help?
> for(i in 1:10) assign(paste('x', i, sep=''), c(i:10))
> ls()
 [1] "i"    "pkg"  "tbbt" "x1"   "x10"  "x2"   "x3"   "x4"   "x5"   "x6"
[11] "x7"   "x8"   "x9"
> for(i in 1:10) print(get(paste('x', i, sep='')))
 [1]  1  2  3  4  5  6  7  8  9 10
[1]  2  3  4  5  6  7  8  9 10
[1]  3  4  5  6  7  8  9 10
[1]  4  5  6  7  8  9 10
[1]  5  6  7  8  9 10
[1]  6  7  8  9 10
[1]  7  8  9 10
[1]  8  9 10
[1]  9 10
[1] 10

Read ?assign, ?get, but also this fortune:
> fortune('assign')

The only people who should use the assign function are those who fully
understand why you should never use the assign function.
   -- Greg Snow
      R-help (July 2009)

I haven't yet figured out why I should heed this. Regards
Liviu


> What I want to do:
>
> Say, I have several data files that differ only in a number, e.g. data
> points (or vector, or matrix...) Data_1, Data_2, Data_3,... and I want to
> manipulate them
>
> e.g. a simple sum of several data points
>
>>data <- c(NA,n)
>>for (i in 1:n){
>>data[i] <- Data_i + Data_[i-1]
>>                  }
>
> I know that the above code doesn't work, and I don't want to combine the
> files into one vector to solve the problem etc. - I would just like to know
> who make sure R recognizes the extension "_i". I have the same problem for
> say, reading in datafiles that only differ by one digit in the extension,
> and I want to (instead of repeating code) combine the process in a loop.
>
> I hope I made myself clear to what my problem is.
>
> Thanks for your help,
>
> //F
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-changing-names-in-loop-in-R-tp3030132p3030132.html
> Sent from the R help mailing list archive at Nabble.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.
>



-- 
Do you know how to read?
http://www.alienetworks.com/srtest.cfm
http://goodies.xfce.org/projects/applications/xfce4-dict#speed-reader
Do you know how to write?
http://garbl.home.comcast.net/~garbl/stylemanual/e.htm#e-mail



More information about the R-help mailing list