Use of offset in lm regression - R

狂风中的少年 提交于 2019-12-30 06:51:13

问题


I've this programme

dens <- read.table('DensPiu.csv', header = FALSE)
fl <- read.table('FluxPiu.csv', header = FALSE)
mydata <- data.frame(c(dens),c(fl))

dat = subset(mydata, dens>=3.15)
colnames(dat) <- c("x", "y")
attach(dat)

and I want to do a least-square regression on the data contained in dat, the function has the form

y ~ a + b*x

and I want the regression line to pass through a specific point P(x0,y0) (which is not the origin).

I'm trying to do it like this

 x0 <- 3.15 

 y0 <-283.56

 regression <- lm(y ~ I(x-x0)-1, offset=y0)

(I think that data = dat is not necessary in this case) but I have this error :

Error in model.frame.default(formula = y ~ I(x - x0) - 1, : variable
 lengths differ (found for '(offset)').

I don't know why. I guess that I haven't defined correctly the offset value but I couldn't find any example on the internet.

Can anybody explain me how offset works please?


回答1:


Your offset term has to be a variable, like x and y, not a numeric constant. So you need to create a column in your dataset with the appropriate values.

dat$o <- 283.56
lm(y ~ I(x - x0) - 1, data=dat, offset=o)



回答2:


In fact, the real issue here is that you should specify offset with a vector whose length is the same as the number of rows (or the length, if data is composed as a vector) of your data. The following code will do your job as expected:

regression <- lm(y ~ I(x-x0)-1, offset = rep(y0, length(y))

Here is a good explanation for those who are interested: http://rfunction.com/archives/223



来源:https://stackoverflow.com/questions/16920628/use-of-offset-in-lm-regression-r

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