Absolute function in R – abs()

Absolute function in R – abs(), computes the absolute value of numeric data.

Syntax for absolute function in R:

abs(x)

x: Numeric value, array or vector

Example of absolute function in R –abs():

#abs function in R - abs

abs(-12.5)

abs(12.5)
output:

[1] 12.5

[1] 12.5

 

 

absolute of vectors in R:

#absolute function in R- abs,for vector

x <- c(-2.2,3.4,0,3.45,8,-4.5)
abs(x)
output:

[1] 2.20   3.40   0.00    3.45    8.00    4.50

 

 

absolute of matrix in R:

# absolute function for matrix in R

x <- matrix(c(-2,3,-5,3,-6,4),nrow=3,ncol=2,byrow=TRUE)
abs(x)

all the negative values of a matrix are turned to positive in above abs function

output:

       [,1] [,2]

[1,]    2    3

[2,]    5    3

[3,]    6    4

 

 

absolute of data frame in R:

lets use the inbuilt sleep data frame in R to demonstrate absolute function for data frame.

# absolute function for a data frame in R

abs(sleep$extra)

in the above example, absolute function is applied to a column named “extra” in sleep data frame.

so the output will be

[1] 0.7   1.6   0.2   1.2   0.1   3.4   3.7   0.8   0.0   2.0   1.9   0.8   1.1   0.1   0.1   4.4    5.5  1.6   4.6   3.4

previous small absolute function in r                                                                                                                next small 23 absolute function in r