Search code examples
rregressionlinear-regressionleast-squares

How to calculate the smallest sum of squared differences among 5 variables


I would like to calculate in Gnu R the smallest sum of squared differences between w,x,y,z and a and choose which of this four variables fits a best, but I have no clue about how to do it in the most elegant way.

Consider the following random data:

set.seed(5840)
a <- runif(100, -1.5, 1.5)
w <- pnorm(rnorm(100))
x <- rnorm(100)
y <- rnorm(100)
z <- dnorm(rnorm(100))

Does somebody know how to do that?


Solution

  • You can use this code:

    sapply(data.frame(w, x, y, z), function(v) sum((a - v) ^ 2))
    #        w         x         y         z 
    # 95.39201 158.81291 186.37518  75.86112 
    

    The smallest sum of squared differences is obtained for z.