Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R abs() Function - Computing Absolute Values

R abs() Function - Computing Absolute Values

R Language Examples R Language Examples

The R abs() function is used to compute the absolute value of a number.

The absolute value of a number is its non-negative value with the sign removed, concerning only the magnitude.

The syntax of the abs() function is as follows:

abs(x)

Parameter Description:

Example

Absolute value of a single number

print

(

abs

(

5

)

)

print

(

abs

(

3.14

)

)

Absolute value of a vector

x

<-

c

(

12

,

27

,

3

,

4.2

,

2

,

0

,

54

,

21

,

4

,

2

)

result.

abs

<-

abs

(

x

)

print

(

result.

abs

)

The output of the code above is:

[1] 5

[1] 3.14

 [1] 12.0 27.0  3.0  4.2  2.0  0.0 54.0 21.0  4.0  2.0

abs() is very commonly used when computing errors:

Example

Predicted and actual values

actual

<-

c

(

100

,

150

,

200

,

250

,

300

)

predicted

<-

c

(

98

,

155

,

195

,

260

,

310

)

Compute absolute error

error

<-

actual

predicted

abs_error

<-

abs

(

error

)

print

(

abs_error

)

Compute mean absolute error (MAE)

mae

<-

mean

(

abs_error

)

print

(

paste

(

"Mean Absolute Error MAE:"

, mae

)

)

The output of the code above is:

[1]  2  5  5 10 10

[1] "平均绝对误差 MAE: 6.4"

R Language Examples R Language Examples