How to find the residual of a glm model in R?

R ProgrammingServer Side ProgrammingProgramming

In a linear model, a residual is the difference between the observed value and the fitted value and it is not different for a general linear model. The difference between linear model and the general linear model is that we use a probability distribution to create a general linear model. If we want to find the residual for a general linear model then resid function can be used just like it is used with the linear model.

Example1

Consider the below data frame:

Live Demo

> x1<-rpois(20,5)
> y1<-rpois(20,2)
> df1<-data.frame(x1,y1)
> df1

Output

 x1 y1
1 4 2
2 3 3
3 5 3
4 4 2
5 9 2
6 6 3
7 3 2
8 7 1
9 9 1
10 5 0
11 8 4
12 9 2
13 2 1
14 6 1
15 6 5
16 6 2
17 5 4
18 8 0
19 10 1
20 3 4

Creating the general linear model and finding the residuals:

Example

> Model1<-glm(y1~x1,data=df1,family="poisson")
> resid(Model1)

Output

1 2 3 4 5 6
-0.26000997 0.27996983 0.47605013 -0.26000997 0.17508623 0.57127286
7 8 9 10 11 12
-0.35255126 -0.77766453 -0.62572768 -2.12094490 1.34735707 0.17508623
13 14 15 16 17 18
-1.18919992 -0.85623706 1.68243725 -0.08061731 1.05078659 -1.93560704
19 20
-0.55225797 0.84384238

Example2

Live Demo

> x2<-rpois(20,1)
> y2<-rpois(20,10)
> df2<-data.frame(x2,y2)
> df2

Output

 x2 y2
1 1 9
2 1 12
3 1 3
4 1 12
5 0 9
6 2 10
7 1 9
8 0 10
9 1 6
10 0 6
11 0 10
12 2 9
13 1 11
14 0 9
15 1 8
16 0 8
17 0 5
18 1 10
19 2 8
20 1 5

Creating the general linear model and finding the residuals:

Example

> Model2<-glm(y2~x2,data=df2,family="poisson")
> resid(Model2)

Output

1 2 3 4 5 6
0.16017237 1.11948460 -2.18804473 1.11948460 0.30245806 0.34329148
7 8 9 10 11 12
0.16017237 0.63543354 -0.91479672 -0.78143829 0.63543354 0.01558047
13 14 15 16 17 18
0.80987101 0.30245806 -0.18271927 -0.04321710 -1.18037107 0.49051583
19 20
-0.32452766 -1.31027760
raja
Published on 23-Nov-2020 10:45:57

Advertisements