tags:

views:

154

answers:

1

Hi all,

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.

Thanks

> 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"
> 
+1  A: 

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)))
Leo Alekseyev