Re: [R] subsetting with column name as string

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Wed, 06 Aug 2008 17:39:35 +0100 (BST)

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

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 06 Aug 2008 - 17:04:42 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 06 Aug 2008 - 17:33:15 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive