R abs Function


abs() function computes the absolute value of numeric data.

abs(x)


x: Numeric value, array or vector

> abs(-1)

[1] 1


> abs(20)

[1] 20


> abs(0)

[1] 0


> x <- c(-2,4,0,45,9,-4)
> abs(x)

[1] 2 4 0 45 9 4


It can calculate all elements of a matrix, or the rows and columns respectively:

> x <- matrix(c(-3,5,-7,1,-9,4),nrow=3,ncol=2,byrow=TRUE)
> x
     [,1] [,2]
[1,]   -3    5
[2,]   -7    1
[3,]   -9    4
> abs(x[1,])

[1] 3 5

> abs(x[,1])
[1] 3 7 9

> abs(x)
     [,1] [,2]
[1,]    3    5
[2,]    7    1
[3,]    9    4


endmemo.com © 2024  | Terms of Use | Privacy | Home