Passing Arguments to Iterated Function Through Apply

Passing arguments to iterated function through apply

You want apply(data,1,FUN,parameter=1). Note the ... in the function definition:

> args(apply)
function (X, MARGIN, FUN, ...)
NULL

and the corresponding entry in the documentation:

...: optional arguments to ‘FUN’.

Passing a function as a parameter to an iterating function in javascript

Lets take a couple of steps back and look at a simpler example.

This is the function you want to call multiple times:

function doSomething(x) {
labels.push(`Unit ${x + 1}`);
}

It takes an argument which it uses to create a string, and pushes that string to an array.

Of course this is easy to do with a loop:

for (let i = 0; i < 5; i++) {
doSomething(i);
}

It should be obvious here that we pass the loop variable (i) to our function, which is assigned to parameter x. It's the same as doing:

doSomething(0);
doSomething(1);
...

This code is not reusable though. Say we want to call the function a different number of times, not just (and always) five times.

We can put the loop in a function itself, taking the number of times as a parameter:

function repeat(n) {
for (let i = 0; i < n; i++) {
doSomething(i);
}
}

Now we can call the function as repeat(5) or repeat(10) and it will call doSomething that many times.

However, now we want to call another function multiple times. We could create a second repeat function (with a different name of course), but that is not ideal.

Instead of referring to doSomething directly in repeat, we can change repeat to accept a second parameter whose value should be a function value. This is possible because functions are values like any other in JavaScript:

function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}

Now we can reuse repeat to call any function we want:

repeat(5, doSomething)
repeat(10, doSomethingElse)

And that's what the code above is doing.

Iterating a Function Using R Lapply and a List of Function Arguments

Use do.call

output <- lapply(arg_sets, function(x) do.call(my_fun, x))

See this simple example,

my_fun <- function(x, y , z) {
x + y + z
}

arg_sets <- list(a = as.list(1:3), b= as.list(4:6))
lapply(arg_sets, function(x) do.call(my_fun, x))

#$a
#[1] 6

#$b
#[1] 15

If instead of list, you create a vector of arguments you can change the above function as

arg_set1 <- c(a1,b1,c1,d1)
arg_set2 <- c(a2,b2,c2,d2)
arg_set3 <- c(a3,b3,c3,d3)
arg_sets <- list(arg_set1, arg_set2, arg_set3)

lapply(arg_sets, function(x) do.call(my_fun, as.list(x)))

How to iterate over function arguments

locals() may be your friend here if you call it first thing in your function.

Example 1:

>>> def fun(a, b, c):
... d = locals()
... e = d
... print e
... print locals()
...
>>> fun(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}

Example 2:

>>> def nones(a, b, c, d):
... arguments = locals()
... print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)
...
>>> nones("Something", None, 'N', False)
The following arguments are not None: a, c, d

Answer:

>>> def foo(a, b, c):
... return ''.join(v for v in locals().values() if v is not None)
...
>>> foo('Cleese', 'Palin', None)
'CleesePalin'

Update:

'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the dict returned by locals() (or vars()) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:

>>> def foo(a, b, c):
... arguments = locals()
... return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)
...
>>> foo(None, 'Antioch', 3)
'Antioch3'

Python - Iterating over Arguments passed to a Function

Use locals() and you can get all the arguments (and any other local variables):

class foo:
def bar(self, w, x, y, z):
argdict = {arg: locals()[arg] for arg in ('w', 'x', 'y', 'z')}
for key, value in argdict.iteritems():
setattr(self, key, value)
...

Might be possible to do it more efficiently, and you could inline argdict if you prefer less lines to readability or find it more readable that way.

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

iterative parameter inside a function - Python

You can pass Xn1 to the function and return Xn1 together with Y every time the function is called. In the first time, it will be either be missing or None (or any other default value of your choice) and then you initialize it.

p.s note that Y is never initialized and so is Xn1 in the original code.

Sketch -

def IterativeFunction(X, Xn1=None):
if Xn1 is None:
Xn1 = initialize
for i in range(len(X)):
Y[i] = 0.1 * X[i] + 0.9 * Xn1
Xn1 = X[i]

return(Y, Xn1)

How to make apply() pass the object in one of the arguments of the function (not the first)?

If I have understood your right, you need to specify the non iterating arguments. For example:

func <- function(a,b,c){
return(a*b + c)
}

apply(FUN=func,a=10,b=10,someObject)

The non specified argument is the argument that is iterated over with your specified vector.

Note that if you have a 1D structure

unlist(lapply(FUN=func,a=10,b=10,someObject))

Will likely work better.

How to efficiently pass function through?

Your code is really far too complex to explain your problem - strive for something simpler. Sometimes you have to write code just to demonstrate the problem.

I'm taking a stab, based purely on your description rather than your code (although I ran the code and verified) . Here's your problem:

method eval: This is the core function to generate the blue, green and
red versions every time. It takes three varying parameters each
iteration: vfunction which is the dominating function from the
previous step, m and s which are two parameters (flaots) affecting the
shape of the resulting curve.

Your vfunction parameter is more complex on each iteration. You are passing a nested function built up over previous iterations, which causes a recursive execution. Each iteration increases the depth of the recursive call.

How can you avoid this? There's no easy or built in way. The simplest answer is - assuming the inputs to these functions are consistent - to store the functional result (i.e. the numbers) rather than the function themselves. You can do this as long as you have a finite number of known inputs.

If the inputs to the underlying functions aren't consistent then there's no shortcut. You need to repeatedly evaluate those underlying functions. I see that you're doing some piecewise splicing of the underlying functions - you can test whether the cost of doing so exceeds the cost of simply taking the max of each of the underlying functions.

The test that I ran (10 iterations) took a few seconds. I don't see that as a problem.

Can we pass parameters to a generator when we iterate it via for..of?

No, it is not possible to pass arguments to next.

function* generateItems() { /* ... */ }
for (var item of generateItems()) {
console.log(item);
}

is mostly short for

function* generateItems() { /* ... */ }
var iterator = generateItems()[Symbol.iterator]();
do {
const result = iterator.next();
if (result.done) break;
const item = result.value;

console.log(item);
} while (true);

barring a few missing try/catch wrappers. You can see in the spec here that it calls .next with no arguments:

Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « »).

e.g.

iterator.next.apply(iterator, []);

calling next() with an empty array of arguments.



Related Topics



Leave a reply



Submit