1

I have list of data frames where I am trying to merge all of the elements of the list into a single data frame by applying merge(). I am looking for a general solution that can handle different functions and large numbers of elements of the list.

For a convenient working example, let's use a related problem that should have the same solution. So, assume we have instead a list of numbers:

foo <- list(1, 2, 478, 676)

Let's further assume that I am trying to write a script that takes the first number and divides it by the second. It then takes that quotient and divides it by the third. It then takes that quotient and divides it by the fourth, etc. In the end, I have a single number stored in a single object. For example:

((foo[1] / foo[2]) / foo[3]) / foo[4]

I have seen rapply() for recursive operations on lists, but all of the examples are for delisting lists and not other operations, such as merge() or arithmetic operations.

QuestionAnswer
  • 321
  • 4
  • 15
  • 1
    `Reduce(function(a,b) a/b, foo)` does what you suggested here, it might not apply to your overall problem. – r2evans Aug 02 '16 at 20:14
  • 2
    Then please update your question with a more appropriate example. We can't help if we don't understand the structure of your data. (Good references: [help/mcve](http://stackoverflow.com/help/mcve) and [reproducible examples](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).) – r2evans Aug 02 '16 at 20:22
  • Are you sure you mean recursively? You don't really have a nested structure in your example? You seem to be describing an iterative process which is exactly what `Reduce` is for. I agree that you need a much better example to make the difference more clear. if you have a list of data.frames, you can merge them with `Reduce(merge, list(data.frame(a=1, b=2), data.frame(a=1, x=10)))` – MrFlick Aug 02 '16 at 20:27

1 Answers1

0

As noted in the comments, using Reduce(function, x) worked, where function is the function to perform on each element of the list and x is the list.

QuestionAnswer
  • 321
  • 4
  • 15