[R] do.call invoking a function with multiple arguments

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Nov 9 09:46:27 CET 2004


On Tue, 9 Nov 2004, Eric Lecoutre wrote:

> I am not sure to understand the help page about do.call.

I think you do, just not how to construct a list.

> --
>   do.call(what, args)
>      args: a _list_ of arguments to the function call.  The 'names'
>            attribute of 'args' gives the argument names.
> --
> 
> If we take the following sample data:
> 
> 
>  > (tab=as.data.frame(table(factor(1:10))))
>     Var1 Freq
> 1     1    1
> 2     2    1
> 3     3    1
> 4     4    1
> 5     5    1
> 6     6    1
> 7     7    1
> 8     8    1
> 9     9    1
> 10   10    1
> 
> I can call "paste" on it:
> 
>  > do.call("paste",tab)
>   [1] "1 1"  "2 1"  "3 1"  "4 1"  "5 1"  "6 1"  "7 1"  "8 1"  "9 1"  "10 1"
> 
> Now if I want to use ":" as the separator, I guess I should write
> 
>  > do.call("paste",list(tab,sep=":"))
> [1] "c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)" "c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)"

But tab is already a list, so you want to concatenate to it.

do.call("paste", c(tab,sep=":"))

Take a look at

str(list(tab,sep=":"))

which shows it is a list of 2 elements, the first of which is a data frame 
(which is a list).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list