R minimizes absolute error

Here is my setup

obs1<-c(1,1,1)
obs2<-c(0,1,2)
obs3<-c(0,0,3)

absoluteError<-function(obs,x){
  return(sum(abs(obs-x)))
}

Example:
> absoluteError(obs2,1)
[1] 2

For a random observation vector, I would like to find a minimizer xthat minimizes the absolute error between the observation values ​​and the vector of all x. For example, it is clear that the minimizing argument absoluteError(obs1,x)is x = 1 because it leads to error 0. How to find a minimizer for a random observation vector? I assume this is a linear programming problem, but I have never implemented it in R. before.

+3
source share
2 answers

The median of generality is a minimizer for absolute error. The following is an example of how you can try to prove this:

Let the median of the set of n observations, obs, be m. Cause an absolute error between obs and mf (obs, m).

n :
f (obs, m + delta), delta - . , - (n-1)/2 +1 , , f (obs, m). (n-1)/2 , f (obs, m). , f (obs, m + delta) -f (obs, m) >= delta. ( , .) , . , f (obs, m + delta) > f (obs, m) , m f.

n :
, , , .

+3

, , , , . , .

, " ", , " ".

, R- :

fabs=function(beta0,x,y){
  b0=beta0[1]
  b1=beta0[2]
  n=length(x)
  llh=0
     for(i in 1:n){
          r2=(y[i]-b0-b1*x[i])
          llh=llh + abs(r2)
     }
  llh
}

g=optim(c(1,1),fabs,x=x,y=y)

:

http://www.stat.colostate.edu/~meyer/hw12ans.pdf

, , , R , , optim.

. , :

y <- c(1,1,1)
x <- 1:length(y)

fabs=function(beta0,x,y){
  b0=beta0[1]
  b1=0
  n=length(x)
  llh=0
    for(i in 1:n){
       r2=(y[i]-b0-b1*x[i])
       llh=llh + abs(r2)
    }
  llh
}

# The commands to get the estimator

g = optim(c(1),fabs,x=x,y=y, method='Brent', lower = (min(y)-5), upper = (max(y)+5))
g

(.. ) . , , .

y <- c(1,1,1) 1 (, , , ):

$par
[1] 1

$value
[1] 1.332268e-15

$counts
function gradient 
      NA       NA 

$convergence
[1] 0

$message
NULL

y <- c(0,1,2) 1:

$par
[1] 1

$value
[1] 2

$counts
function gradient 
      NA       NA 

$convergence
[1] 0

$message
NULL

y <- c(0,0,3) 0 (, , ):

$par
[1] 8.613159e-10

$value
[1] 3

$counts
function gradient 
      NA       NA 

$convergence
[1] 0

$message
NULL

R , R , .

, , .

, , - ( ) 24 .

, , .

+2

All Articles