Weighted linear regression in R

MikeP picture MikeP · Nov 11, 2015 · Viewed 14.1k times · Source

I would like to do a linear regression with a weighting factor for an analytical chemistry calibration curve. The x values are concentration and assumed to have no error. The y values are instrument response and the variation is assumed proportional to concentration. So, I would like to use a 1/x weighting factor for the linear regression. The data set is simply ten concentrations with a single measurement for each. Is there an easy way to do this in R? .

Answer

kneijenhuijs picture kneijenhuijs · Nov 11, 2015

The answer can be found on a somewhat older question on Cross Validated. The lm() function (which represents the usual method of applying a linear regression), has an option to specify weights. As shown in the answer on the link, you can use a formula in the weights argument. In your case, the formula will likely take the form of 1/data$concentration.

As suggested by hrbrmstr, I'm adding mpiktas's actual answer from Cross Validated:

I think R help page of lm answers your question pretty well. The only requirement for weights is that the vector supplied must be the same length as the data. You can even supply only the name of the variable in the data set, R will take care of the rest, NA management, etc. You can also use formulas in the weight argument. Here is the example:

x <-c(rnorm(10),NA) df <-
data.frame(y=1+2*x+rnorm(11)/2,x=x,wght1=1:11)

##Fancy weights as numeric vector 
summary(lm(y~x,data=df,weights=(df$wght1)^(3/4))) 

#Fancy weights as formula on column of the data set
summary(lm(y~x,data=df,weights=I(wght1^(3/4))))

#Mundane weights as the column of the data set
summary(lm(y~x,data=df,weights=wght1)

Note that weights must be positive, otherwise R will produce an error.