[R] subsetting with column name as string

Dan Davison davison at stats.ox.ac.uk
Wed Aug 6 18:44:27 CEST 2008


On Wed, Aug 06, 2008 at 11:53:25AM -0400, 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.
>                                                            Thanks, Faheem.

To get the behaviour you were expecting, the definition should have been

foo <- function(val) d[[val]]

Look at the indexing help page

help("$")

It says
   Usage:

     <...>
     x$name
     <...>
    name: A literal character string or a name...

and then further down, in the section on indexing lists

   'x$name' is equivalent to 'x[["name", exact = FALSE]]'.

So, d$val looks for an element called 'val' and doesn't find
one. d[["val"]] would do the same.  However d[[val]] looks for an
object called 'val', and then tries to use its value to index into d.

Dan
>
> ______________________________________________
> 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.



More information about the R-help mailing list