Skip to content
Prev 345792 / 398502 Next

Using sapply instead of for loop

Amit,

Even if you aren't getting an error with your original global variables it
is far better practice to avoid global variables to make you code much more
stable.  Of course you ultimately get to decide how your code is written.

That said, your error from the modified far function to include the
variables is because you added too much to the sapply statement.  Here is
what it should look like:

            A<-sapply((1:Permax),function(p) far(p, i, j, k, l, m,n,
ervalue),simplify=FALSE)

You can think apply statements as nothing more than a for loop that has
been made 'pretty'.  You wanted to iterate from 1:Permax and use the other
variables, therefore you only have the anonymous function (i.e.
function(p)) only include the iterator and supply the other values from
your nested for loops to the function.  When I run this with you code,
making sure the function accepts the extra parameters, the A array appears
to fill appropriately whereby most are 'NA' as specified by your 'far'
function.  Is this what you expect?


On Wed, Nov 19, 2014 at 8:16 AM, Amit Thombre <amitmt at techmahindra.com>
wrote: