Re: [R] Loop for in R to generate several variables

From: Barry Rowlingson <b.rowlingson_at_lancaster.ac.uk>
Date: Mon, 07 Apr 2008 12:24:48 +0100

Gustaf Rydevik wrote:
> On Mon, Apr 7, 2008 at 11:31 AM, arpino <bruno.arpino@unibocconi.it> wrote:

>>  Hi everybody,
>>  I have to create several variables of this form:
>>
>>  Yind = L0 + L1*X1 + L2*X2 + L3*X3 + K*Cind + n
>>
>>  where ind varires in {1,...,10}

>
> look up ?assign and ?get, i.e:
> for (ind in 1:10) {
> assign(paste("Y",ind,sep=""),L0 + L1*X1 + L2*X2 + L3*X3 +
> get(paste("C",ind,sep=""))+ n)
> }

  EXCEPT you probably don't really want to do that.

  Much much better to store the results in a list(), so you can access each element in a much more obvious way, with an integer index, unlike that faffing with assign() and get().

  Y=list()
  for(ind in 1:10){
   Y[[ind]] = foo(ind)
  }

  Then Y[[1]] and so on gives you the values.

Barry



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 Mon 07 Apr 2008 - 11:20:11 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 Mon 07 Apr 2008 - 12:30:26 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