Reputation: 1025
Is there any way to refer to the attributes of the objects by some other variable in R? The following example will explain, what I mean.
Let's say we have an object with some attributes - the kind of object is not important for the question. For example we can have
x <- 1:100
y <- x+rnorm(100)
obj <- lm(y~x+1)
Now I would like to write a function with an argument that would refer to one specific attribute of an object. For example, I would like to write a function, which would print values of some attributes of the created object. Specifically I want to have something like this:
fun <- function(obj, attr) {
print(obj$attr)
}
My question is, what is the way to refer to an attribute of an object by some other variable. I know that the example is silly, but I want to call attention to the problem, not to the function.
Thanks in advance
Kuba
Upvotes: 1
Views: 600
Reputation: 121598
You can use something like :
fun <- function(obj, attr) {
print(obj[[attr]])
}
For example ,
fun(obj,'call')
lm(formula = y ~ x + 1)
Upvotes: 4