[R] Using changing names in loop in R

Daniel Nordlund djnordlund at frontier.com
Sat Nov 6 19:57:40 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
> On Behalf Of Tuatara
> Sent: Saturday, November 06, 2010 9:22 AM
> To: r-help at r-project.org
> Subject: [R] Using changing names in loop in R
> 
> 
> 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:
> 
> 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,
> 

This is one of those cases where a commented, self-contained, reproducible example would be very helpful in helping you.  You mention you have several "data files", but I see no reference to data files in your code.  Did you mean data frames?  What is Data_i?  A data frame or something else?

You said you normally do this by repeating lines of code.  Can you show us a simple example?  Someone should be able to show you how to optimize it.

Dan

Daniel Nordlund
Bothell, WA USA
 



More information about the R-help mailing list