开发者

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

This question already has answers here: Dynamically select data开发者_开发知识库 frame columns using $ and a character value (10 answers) Closed 6 years ago.

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.

  • 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜