How to fix the coefficient of an independent variable in R?

R ProgrammingServer Side ProgrammingProgramming

While doing the analysis we might know the variation in an independent variable or we might want to understand how other independent variables behave if we fix a certain variable. Therefore, we can fix the coefficient of an independent variable while creating the model and this can be done by using offset function with the coefficient of the variable for which we want to fix the value of the coefficient.

Example

Consider the below data frame:

Live Demo

> set.seed(854)
> x1<-rnorm(20,5,0.34)
> x2<-rnorm(20,5,1.96)
> y1<-rnorm(20,10,1.20)
> df1<-data.frame(x1,x2,y1)
> df1

Output

     x1       x2       y1
1  5.055384 4.179533 10.432503
2  4.504170 4.239420  9.965098
3  4.790987 6.854590 12.394971
4  5.225883 5.302747  9.959724
5  5.331538 7.986233 10.652037
6  5.437044 4.479045 10.631804
7  4.880098 6.737453 11.647296
8  5.027229 3.380460 10.336230
9  5.114676 5.252512 10.005986
10 4.971399 3.423199 10.892680
11 5.360185 8.004727 10.988475
12 4.938459 6.348125 7.740576
13 5.490242 5.362272 8.400993
14 5.104938 4.410061 8.559530
15 5.680805 4.225577 9.805985
16 5.321608 5.213297 8.401131
17 5.095157 8.048281 10.927522
18 5.153315 2.422241 9.090280
19 5.534677 2.886866 8.402550
20 4.625666 4.487508 9.957264

Creating a model for predicting y1 by fixing the coefficient of x2:

> Model1<-lm(y1~x1+offset(5*x2),data=df1)
> summary(Model1)

Call:

lm(formula = y1 ~ x1 + offset(5 * x2), data = df1)

Residuals:

  Min       1Q     Median 3Q    Max
-13.4830 -6.2440 0.9653 4.9613 12.8422

Coefficients:

Estimate Std. Error t value Pr(>|t|)
(Intercept) -13.0038 32.2757 -0.403 0.692
x1 -0.5549 6.2786 -0.088 0.931

Residual standard error: 8.269 on 18 degrees of freedom

Multiple R-squared: 0.5247, Adjusted R-squared: 0.4983

F-statistic: 19.87 on 1 and 18 DF, p-value: 0.0003043

Example

Let’s have a look at another example:

Live Demo

> a1<-rpois(20,5)
> a2<-rpois(20,8)
> Response<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(a1,a2,Response)
> df2

Output

  a1 a2 Response
1  3  7   8
2  7 11   8
3 10  8   3
4  6  5   6
5  4  5   8
6 16 10   7
7  4  8  10
8  5 11   1
9  6  4   4
10 5 12   2
11 5  9   7
12 5  8   8
13 7  6   2
14 2 10   9
15 5 10   1
16 5  6  10
17 2  6   7
18 6 11   1
19 8 12   1
20 4 11   4

Creating a model for predicting Response by fixing the coefficient of a1:

> Model2<-lm(Response~offset(1.34*a1)+a2,data=df2)
> summary(Model2)

Call:

lm(formula = Response ~ offset(1.34 * a1) + a2, data = df2)

Residuals:

Min 1Q Median 3Q Max
-10.890 -3.164 1.325 3.358 9.870

Coefficients:

Estimate Std. Error t value Pr(>|t|)
(Intercept) 4.4180 4.4255 0.998 0.331
a2 -0.7968 0.4998 -1.594 0.128

Residual standard error: 5.543 on 18 degrees of freedom

Multiple R-squared: 0.3836, Adjusted R-squared: 0.3494

F-statistic: 11.2 on 1 and 18 DF, p-value: 0.003587

raja
Updated on 06-Nov-2020 11:09:08

Advertisements