define $ right parameter with a variable in R [duplicate]
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.
- 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
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