The abs() function in R is used to calculate absolute values. If you still have no idea what it is and how to use it then please check out our instructions below because we will show you the syntax and some of the most common applications of the abs() function.
Abs() function in R
What does the abs() function do in R?
The abs() function will return the absolute value of a given value. So, the positive value will remain positive and the negative value will become positive.
Syntax:
abs(value)
Parameter:
- value: the value that you want to get the absolute value.
Return value: the absolute value of the given value.
How to use abs() in R
Get absolute value of numbers
# Get absolute value of a number num = -12 abs(num)
Output:
[1] 12
Get absolute value of vectors
# Get the absolute value of a vector vector <- c(-2, -21, 5, -8, -91, 12, 56, -74) abs(vector)
Output:
[1] 2 21 5 8 91 12 56 74
Get absolute value of a data frame/matrix
First, let’s use the replicate() function and rnorm() function to create a 5×6 data frame that is made by random numbers, with a given mean value of -2 and given standard deviation of 1.
data <- replicate(5, rnorm(6, mean=-2, sd=1)) data
[,1] [,2] [,3] [,4] [,5]
[1,] -1.0158515 -2.553593 -1.113710 -2.6236427 -2.110614
[2,] -0.7072976 -3.116418 -1.607698 -2.3030443 -1.839129
[3,] -1.2034758 -2.011888 -1.328349 -0.9884317 -1.532758
[4,] -0.7775238 -1.830390 -1.678170 -1.1938798 -1.685372
[5,] -2.5375438 -1.724360 -3.935374 -2.5529615 -1.514231
[6,] -2.0132275 -1.838443 -1.972373 -1.0432227 -2.036202
Now, when we use the abs() function with this data frame, it will convert all the negative numbers in this data frame into positive numbers.
data <- replicate(5, rnorm(6, mean=-2, sd=1)) abs(data)
Output:
[,1] [,2] [,3] [,4] [,5]
[1,] 1.0158515 2.553593 1.113710 2.6236427 2.110614
[2,] 0.7072976 3.116418 1.607698 2.3030443 1.839129
[3,] 1.2034758 2.011888 1.328349 0.9884317 1.532758
[4,] 0.7775238 1.830390 1.678170 1.1938798 1.685372
[5,] 2.5375438 1.724360 3.935374 2.5529615 1.514231
[6,] 2.0132275 1.838443 1.972373 1.0432227 2.036202
Summary
In this tutorial, we have shown you the syntax and how to use the abs() function in R. Basically, the abs() function will calculate the absolute value. We can use it with numbers, vectors, or even a whole data frame.
Maybe you are interested:
- Optimize() function in R: How To Use The Optimize Function in R
- How To Merge Rows In R
- How To Merge CSV Files In R

Hello. My name is Khanh Hai Ngo. I graduated in Information Technology at VinUni. My advanced programming languages include C, C++, Python, Java, JavaScript, TypeScript, and R, which I would like to share with you. You will benefit from my content.
Name of the university: VinUni
Major: EE
Programming Languages: C, C++, Python, Java, JavaScript, TypeScript, R