How to add regression residuals to data frame in R?

R ProgrammingServer Side ProgrammingProgramming

To add regression residuals to data frame in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use lm function to create the regression model and find the residuals using resid function and adding them to the data frame with $ operator.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-sample(1:50,20)
y<-sample(1:50,20)
df<-data.frame(x,y)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  x y
1 6 36
2 14 49
3 45 39
4 1 11
5 25 23
6 36 42
7 43 28
8 3 48
9 44 24
10 31 29
11 40 25
12 18 50
13 19 12
14 7 8
15 17 27
16 21 20
17 37 35
18 35 38
19 23 26
20 8 30

Create the regression model and add residual to the data frame

Using lm function to create the regression model then finding the residuals and adding them to the data frame with $ operator −

 Live Demo

x<-sample(1:50,20)
y<-sample(1:50,20)
df<-data.frame(x,y)
Model<-lm(y~x)
df$Residuals<-Model$resid
df

Output

    x y Residuals
1   6 36 7.739155
2   14 49 19.950870
3   45 39 6.896262
4   1 11 -16.768166
5   25 23 -7.133023
6   36 42 10.783084
7   43 28 -3.906666
8   3 48 20.034763
9   44 24 -8.005202
10  31 29 -1.724238
11  40 25 -6.611059
12  18 50 20.556727
13  19 12 -17.541809
14  7 8 -20.359380
15  17 27 -2.344737
16  21 20 -9.738880
17  37 35 3.684548
18  35 38 6.881620
19  23 26 -3.935952
20  8 30  1.542084
raja
Published on 04-Aug-2021 11:33:41

Advertisements