R abs() Function - Computing Absolute Values
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:
-
x Input number or numeric vector.
Example
Absolute value of a single number
(
abs
(
5
)
)
(
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
)
(
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
)
(
abs_error
)
Compute mean absolute error (MAE)
mae
<-
mean
(
abs_error
)
(
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