Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define $ right parameter with a variable in R [duplicate]

Tags:

r

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
like image 977
Liborio Francesco Cannici Avatar asked Jun 20 '10 13:06

Liborio Francesco Cannici


3 Answers

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

my_helper <- function (my_param) {
  levels(diamond[[my_param]])
}
my_helper("cut")
like image 177
hadley Avatar answered Oct 13 '22 18:10

hadley


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.

  • https://stackoverflow.com/questions/192369/books-for-learning-the-r-language
  • What are some good books, web resources, and projects for learning R?
  • https://stackoverflow.com/questions/1204043/good-intro-books-for-r
like image 41
Dirk Eddelbuettel Avatar answered Oct 13 '22 16:10

Dirk Eddelbuettel


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
like image 43
FloE Avatar answered Oct 13 '22 17:10

FloE