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
Use [[
instead of $
. x$y
is short hand for x[["y"]]
.
my_helper <- function (my_param) {
levels(diamond[[my_param]])
}
my_helper("cut")
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With