tags:

views:

97

answers:

3

I would like to pass a variable to the binary operator $.

Let's say I have this

> levels(diamonds$cut)
[1] "Fair"      "Good"      "Very Good" "Premium"   "Ideal" 

Then I want to make a function that takes as parameter the selector for $

my_helper <- function (my_param) {
  levels(diamonds$my_param)
}

But this doesn't work

> my_helper(cut)
NULL

> my_helper("cut")
NULL
+1  A: 

You cannot access components of an object without having access to the object itself, which is why your my_helper() fails.

It seems that you are a little confused about R objects, and I would strongly recommend a decent introductory texts. Some good free ones at the CRAN sites, and there are also several decent books. And SO had a number of threads on this as e.g.

Dirk Eddelbuettel
why do you say he does not have access to the object? I assume `diamonds` is in the global scope, the problem is that `$` does not accept strings.
nico
That is technically correct but wrong-headed -- don't assume global visibility but make your accessor functions explicit. And the whole approach is wrong, hence the need for some more thorough reading. If you must, `mylevels <- function(x,y) levels(x[,y])` should work --- but there is more to learn about lists, data.frames, ... and what to use when. Plus the need for testing whether the name exists, the object is appropriate etc pp
Dirk Eddelbuettel
I disagree to some extent - in some cases during interactive data analysis (not programming) it can be useful to define small helper functions that rely on a fixed data set name.
hadley
Dirk, I think I am more confused about operators then objects. $ accepts only strings but with no quotation so I can't do x$myvar because it implicitly convert myvar into "myvar". On the other hand one can use x[["y"]] that works fine with x[[myvar]]. Anyway thank you a lot for helping!
Libo Cannici
+1  A: 

Hi,

Try something like this:

dat = data.frame(one=rep(1,10), two=rep(2,10), three=rep(3,10))
myvar="one"
dat[,names(dat)==myvar]

This should return the first column/variable of the data frame dat

dat$one --> [1] 1 1 1 1 1 1 1 1 1 1
FloE
You don't need the `names(dat)==myvar`, just pass in `myvar'.
Dirk Eddelbuettel
of course you are right - I prefer redundant examples to show what is really going on ;)
FloE
+5  A: 

Use [[ instead of $. x$y is short hand for x[["y"]].

my_helper <- function (my_param) {
  levels(diamond[[my_param]])
}
my_helper("cut")
hadley