5

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
David Arenburg
  • 91,361
  • 17
  • 137
  • 196

3 Answers3

10

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

my_helper <- function (my_param) {
  levels(diamond[[my_param]])
}
my_helper("cut")
hadley
  • 102,019
  • 32
  • 183
  • 245
1

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.

Community
  • 1
  • 1
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 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 Jun 20 '10 at 14:20
  • 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 Jun 20 '10 at 14:38
  • 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 Jun 20 '10 at 16:00
  • 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! – Liborio Francesco Cannici Jun 20 '10 at 19:56
1

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
  • 1,166
  • 1
  • 10
  • 19