[R] Using '[' as a function

peter dalgaard pdalgd at gmail.com
Wed Aug 4 13:42:01 CEST 2010


On Aug 3, 2010, at 7:59 PM, Johann Hibschman wrote:

> Duncan Murdoch <murdoch.duncan at gmail.com> writes:
>> On 29/07/2010 6:18 PM, chipmaney wrote:
>>> 
>>> -Why does R recognize '[' as a function?  
>> 
>> Because it is a function.
> 
> More explicitly, '[' is a string.  sapply then calls match.fun to look
> up that string to get the function named '['.
> 
>>> -Why does it need the quotes?
>> 
>> Because sapply(example,[,1) would not be syntactically valid.
> 
> And, luckily enough, sapply uses the match.fun machinery to allow string
> names for functions.  This is also useful to ensure late binding of
> functions in other contexts.

Also note the `[` (backtick) notation, which avoids using string names for non-syntactic names. (This was a relatively late (2003) addition to the R language, introduced to handle situations where strings would not substitute for function names. The older option of using strings for functions was retained for compatibility.)


-- 
Peter Dalgaard
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



More information about the R-help mailing list