How to fit predefined offsets to models containing categorical variables in R

雨燕双飞 提交于 2020-01-14 05:30:11

问题


Using the following data:

http://pastebin.com/4wiFrsNg

I am wondering how to fit a predefined offset to the raw relationship of another model i.e. how to fit the estimates from Model A, thus:

ModelA<-lm(Dependent1~Explanatory)

to model B thus:

ModelB<-lm(Dependent2~Explanatory)

Where the explanatory variable is either the variable "Categorical" in my dataset, or the variable "Continuous". I got a useful answer related to a similar question on CV:

https://stats.stackexchange.com/questions/62584/how-to-fit-a-specific-model-to-some-data

Here the exaplantory variable was "Continuous". However I had some extra questions I needed answering that I thought might be more suited to SO. If this is not the case, tell me and I will delete this question :)

Specifically, I was advised in the link above that in order to fit a predefined slope for the continuous explanatory variable in my dataset I should do this:

lm( Dependent2 ~ 1 + offset( Slope * Continuous ) )

Where slope is the predefined slope taken from from Model A. Which worked great.

Now I am wondering, how do I do the same when x is a categorical variable with two levels, and then when x is a continuous variable with a quadratic term i.e. x+x^2?

For the quadratic term I am trying:

lm( Dependent2 ~ 1 + offset( Slope * Continuous )+ offset( Slope2 * I((Continuous)^2)) )

Where Slope is the value for the fixed estimate of for Continuous term, and Slope2 is the value for the fixed estimate of the quadratic term.

I am unsure how to get this working for a categorical variable however. When I try to fit an offset as:

lm( Dependent2 ~ 1 + offset( Slope * Categorical ) )

where again, slope is the slope value of the fixed estimate taken from Model A, I get an error:

"Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :   0 (non-NA) cases
In addition: Warning message:
In Ops.factor(0.25773, Categorical) : * not meaningful for factors"

If anyone has an input on how to create offsets for categorical variables it would be greatly appreciated :)


回答1:


The best you can probably do is compute the offset manually for each level of your factor:

x <- rep(1:3, each=10)
df <- data.frame(x=factor(x), y=3 - x)

# compute the offset for each level of x
df$o <- with(df, ifelse(x == "1", 2, ifelse(x == "2", 1, 0)))

# fitted coef's for the models below will all be zero due to presence of offset
lm(y - o ~ x - 1, data=df)
# or
lm(y ~ x + offset(o), data=df)


来源:https://stackoverflow.com/questions/17319689/how-to-fit-predefined-offsets-to-models-containing-categorical-variables-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!