[R] What is the difference between Reduce(…) and do.call(…) ?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Oct 8 11:46:14 CEST 2013


On Tue, Oct 8, 2013 at 10:22 AM, Asis Hallab <asis.hallab at gmail.com> wrote:
> Dear R-Experts,

> So, what is the difference between Reduce and do.call and when best to
> use which?

>From the help:

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

  ‘do.call’ constructs and executes a function call from a name or a
     function and a list of arguments to be passed to it.


 In your example, rbind gets called N-1 times when using Reduce (where
N is the length of the list) because it is doing something like:

 rbind(x[[1]],rbind(x[[2]],x[[3]]))

For longer lists, its doing something like (where a b c d e are list
elements x[[1]] to x[[5]])

rbind( a, rbind( b, rbind( c, rbind( d, e ) ) ) )

whereas do.call calls it once, as rbind(a,b,c,d,e)

Use Reduce when you are doing a Reduce operation (read up on
Functional Programming). Use do.call when you want to call a function
with parameters in a list.

Barry



More information about the R-help mailing list