[R] subsetting with column name as string
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed Aug 6 18:39:35 CEST 2008
On Wed, 6 Aug 2008, Faheem Mitha wrote:
>
> Hi,
>
> Consider the following
>
>> x = c(1,2)
>> y = c(3,4)
>> d = data.frame(cbind(x,y))
>> d$x
> [1] 1 2
>> d$"x"
> [1] 1 2
>>
>> foo = function(val)
> + {
> + return(d$val)
> + }
>>
>> bar = function()
> + {
> + return(d$"x")
> + }
>>
>> foo("x")
> NULL
>> bar()
> [1] 1 2
>
> I'm a little surprised that R accepts both the form d$x and d$"x", but I'm
> mostly wondering why foo("x") doesn't work.
It does work: it returns d$val as instructed. From the help
Usage:
x$name
name: A literal character string or a name (possibly backtick
quoted).
or see the version in ?`$.data.frame`.
So you are 'a little surprised' that the function works as described on
the help page! Please explain to us how you can to that conclusion.
I think you are looking for [[ (on the same help page as $).
> Thanks, Faheem.
--
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