Cookie
Cookie

Reputation: 12662

Repeatedly re-apply 2 argument function using result of previous call

I would like to repeatedly apply a function which takes two arguments to a list, using the result of the first call with the third argument for the second call and so forth and such.

e.g. if the list has 4 elements, and given a function f, I want the result to be f(f(f(1,2),3),4). Does such a function exist?

An example would be to have a list of dataframes, which should all be merged on a specific column.

Upvotes: 1

Views: 207

Answers (1)

johannes
johannes

Reputation: 14433

One way to call a function recursively is to use Reduce. From ?Reduce:

‘Reduce’ uses a binary function to successively combine the elements of a given vector and a possibly given initial value.

You could merge several data.frame from a list like this:

# some dummy data
a <- list(data.frame(a=1:10, b=rnorm(10)), data.frame(a=1:10, b=rnorm(10)), data.frame(a=1:10, b=rnorm(10)))

Reduce(function(u, v)  cbind(u, v$b) , a)
    a          b        v$b         v$b
1   1 -1.2968741 -0.4186869  0.29888504
2   2 -0.2680551  0.3315939  2.05348116
3   3 -0.5188585  0.5125005  1.95103927
4   4 -0.7447659 -1.2982199  0.80582874
5   5  0.2391337 -0.6818633 -0.75994882
6   6 -0.6391927  0.3584701  1.50356731
7   7  1.0117809 -0.1060888  0.07402643
8   8 -1.8877719 -0.4380313  0.49141877
9   9 -0.7392668  1.1527095  1.40168828
10 10 -1.0318087  0.1889492  1.39867700

Upvotes: 4

Related Questions