[R] Constructing a matrix of outputs from loop

David Winsemius dwinsemius at comcast.net
Tue Jul 9 02:43:17 CEST 2013


On Jul 8, 2013, at 2:14 PM, Bert Gunter wrote:

> David:
> 
> Perhaps not. func() must be vectorized for this to work.
> 
> -- Bert
> 
> 
> On Mon, Jul 8, 2013 at 2:06 PM, David Carlson <dcarlson at tamu.edu> wrote:
>> ?outer
>> 
>> e.g. output <- outer(ap, am, func)
>> 
>> -------------------------------------
>> David L Carlson
>> Associate Professor of Anthropology
>> Texas A&M University
>> College Station, TX 77840-4352
>> 
>> -----Original Message-----
>> From: r-help-bounces at r-project.org
>> [mailto:r-help-bounces at r-project.org] On Behalf Of Edward Patzelt
>> Sent: Monday, July 8, 2013 3:15 PM
>> To: r-help at r-project.org
>> Subject: [R] Constructing a matrix of outputs from loop
>> 
>> R -
>> 
>> I would like to construct a matrix from the output of a loop that
>> has 2
>> values it varies over the course of the loop creating a 20x20 matrix
>> of
>> output values:
>> 
>> ap = logspace(-3, 0, 20)
>> 
>> am = logspace(-3, .7, 20)
>>  for (ap in apList)
>>  {
>>   for (am in amList)
>>   {
>> 
>> output = func(ap, am)
>> }
>> }
>> 

You are overwriting each prior value of "output" since you are not indexing your assignments into a matrix. (You also didn't tell us where `logspace` comes from:

> ?logspace
No documentation for ‘logspace’ in specified packages and libraries:
you could try ‘??logspace’

Nonetheless:

apVec = logspace(-3, 0, 20)
amVec = logspace(-3, .7, 20)
output <- matrix(NA, ncol=length(apVec), nrow=length(amVec) )
 for (ap in seq_along( apVec)) {
   for (am in seq_along(amVec) ) {
     output[am, ap]  = func( apVec[ap], amVec[am] )
  }  
 }


>> i.e. cell 1x1 is -3,-3 and the value is 45 or something
>> 
>> --
>> *Edward H Patzelt | Research Assistant


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list