Absolute function in R – abs()

Absolute function in R – abs(), computes the absolute value of numeric data. abs() function in R is used to get the absolute value of Column in a dataframe, Absolute value of the matrix and vectors. Let’s see an example for each on how absolute method is used.

Absolute function in R – abs() 0

 

Syntax for absolute function in R:

 #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 value of column in R data frame :

lets use the below data frame in R to demonstrate absolute method for data frame.

Absolute function in R – abs() 1

# absolute function for a data frame in R

df$Absolute_Score = abs(df$Score)
df

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

so the output will be
Absolute function in R – abs() 2

 

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

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.