[R] subsetting with column name as string

milton ruser
Wed, 06 Aug 2008 16:20:05 -0000

Try this


foo1 = function(val)
 {
   return(d[val])
 }

foo1("x")


Good luck

miltinho astronauta
brazil



On 8/6/08, Faheem Mitha <faheem@email.unc.edu>
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.
>
> ______________________________________________
> R-help@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<http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]