Guest User

Untitled

a guest
Jul 17th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. x<-c(1:50)
  2. y<-x+rnorm(50,sd=10)
  3.  
  4. plot(x,y,pch=20,main="Distance from Fitted Line")
  5. abline(coef(lm(y~x)[1],coef(lm(y~x)[2])),col="blue",lwd=2)
  6. segments(x,predict(lm(y~x)),y1=lm(y~x)$model[,1])
  7.  
  8. #This bit took longer to do than I care to admit. Basically you want distance from the data point to the line
  9. #as an adjacent side to the triangle that would have the vertical distance as the hypotenuse.
  10. #Because I don't know how to tell R to draw a segment with a given slope and starting point, I have to give
  11. #the start and end points. In order to get that I compute the rise and run via similar triangles.
  12. #x.shift and y.shift do most of the work in a vectorized computation.
  13. x.shift<- sin(atan(-1/coef(lm(y~x))[2]))*cos(atan(-1/coef(lm(y~x))[2]))*sqrt((simple.y[,2]-simple.pred[,2])^2)
  14. y.shift<- sin(atan(-1/coef(lm(y~x))[2]))*sin(atan(-1/coef(lm(y~x))[2]))*sqrt((simple.y[,2]-simple.pred[,2])^2)
  15. #The for loop is here because we need to change the rise/run from positive to negative depending on whether or not
  16. #the data point is above or below the regression line.
  17. for (i in 1:50) {
  18. if (simple.y[i,2]>simple.pred[i,2]) {
  19. x.shift[i]<- -x.shift[i]
  20. y.shift[i]<- -y.shift[i]
  21. }
  22. }
  23.  
  24. plot(x,y,pch=20,main="Transformed Distance from Fitted Line")
  25. abline(coef(lm(y~x)[1],coef(lm(y~x)[2])),col="blue",lwd=2)
  26. segments(x,y,x0=x+x.shift,y0=y+y.shift)
Add Comment
Please, Sign In to add comment