[R] syntax with do.call and `[`
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed Aug 3 16:40:32 CEST 2011
On Wed, 3 Aug 2011, peter dalgaard wrote:
>
> On Aug 3, 2011, at 12:30 , Jannis wrote:
>
>> Dear List,
>>
>>
>>
>> i would like to mimic the behaviour or the following indexing with a do.call construct to be able to supply the arguments to `[` as a list:
>>
>>
>> test = matrix[1:4,2]
>>
>> result = test[2,]
>>
>>
>> My try, however, did not work:
>>
>> result = do.call(`[`,list(test,2,NULL))
>> result = do.call(`[`,list(test,2,))
>> result = do.call(`[`,list(test,2,''))
>>
>>
>> How can I use the do.call in that way with leaving the second indexing vector blanc?
>>
>
> alist() actually allows this, although probably more by coincidence than by design.
>
> Watch:
>
>> do.call(`[`, alist(test, 2, ))
> [1] 2 4
>
> If you want to turn this into a programming idiom, be aware that there are subtle differences because alist() does not evaluate its arguments. E.g., the two plots below are not quite the same.
>
>> x <- 1:10
>> y <- rnorm(10)
>> do.call(plot, list(x, y))
>> do.call(plot, alist(x, y))
I decided to forbear suggesting that, not least as someone who writes
>> test = matrix[1:4,2]
appears to know very little R and test even less.
But for indexing the answer could be something like
do.call(`[`, list(test, 2, TRUE))
as in almost all cases (including here) an empty index is equivalent
to TRUE (which is recycled to the required length).
> --
> Peter Dalgaard, Professor,
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
--
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