Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do introspection in R

Tags:

r

I am somewhat new to R, and i have this piece of code which generates a variable that i don't know the type for. Are there any introspection facility in R which will tell me which type this variable belongs to?

The following illustrates the property of this variable:

I am working on linear model selection, and the resource I have is lm result from another model. Now I want to retrieve the lm call by the command summary(model)$call so that I don't need to hardcode the model structure. However, since I have to change the dataset, I need to do a bit of modification on the "string", but apparently it is not a simple string. I wonder if there is any command similar to string.replace so that I can manipulate this variable from the variable $call.

> str<-summary(rdnM)$call
> str
lm(formula = y ~ x1, data = rdndat)
> str[1]
lm()
> str[2]
y ~ x1()
> str[3]
rdndat()
> str[3] <- data
Warning message:
In str[3] <- data :
  number of items to replace is not a multiple of replacement length
> str
lm(formula = y ~ x1, data = c(10, 20, 30, 40))
> str<-summary(rdnM)$call
> str
lm(formula = y ~ x1, data = rdndat)
> str[3] <- 'data'
> str
lm(formula = y ~ x1, data = "data")
> str<-summary(rdnM)$call
> type str
Error: unexpected symbol in "type str"
> 
like image 450
Lebron James Avatar asked Mar 18 '10 03:03

Lebron James


1 Answers

In terms of introspection: R allows you to easily examine and operate on language objects.
For more details, see R Language Definition, particularly sections 2 and 6. For instance, in your case, summary(rdnM)$call is a "call" object. You can retrieve pieces of it by indexing, but you can't construct another call object by assigning to indices like you are trying to do. You'd have to construct a new call.

In your case you are constructing an updated call to lm() out of an existing call. If you want to reuse the formula on different data, you would extract the formula from the call object via formula(foo$call), like so:

 foo <- lm(formula = y ~ x1, data = data.frame(y=rnorm(10),x1=rnorm(10)))
 bar <- lm(formula(foo$call), data = data.frame(y=rnorm(10),x1=rnorm(10)))

On the other hand, if you are trying to update the formula, you could use update():

baz <- update(bar, . ~ . - 1)
baz$call
##>lm(formula = y ~ x1 - 1, data = data.frame(y = rnorm(10), x1 = rnorm(10)))
like image 113
Leo Alekseyev Avatar answered Oct 26 '22 03:10

Leo Alekseyev