Skip to Content

Get the Absolute Value in R using abs()

In this tutorial, we will look at how to get the absolute value for a variable (or values in a vector) in R with the help of some examples.

How to get the absolute value of a number in R?

You can use the built-in math function abs() to get the absolute value (magnitude without the sign) of a number in R. Pass the number for which you want to get the absolute value as an argument to the abs() function. The following is the syntax –

abs(x)

It returns the number without any sign. That is, if you pass a negative number, it will return the number without the negative sign and if you pass a positive number, it will return the same number.

Note that you can apply the abs() function to a vector, array, matrix, and a dataframe as well.

Examples

Let’s look at some examples of using the abs() function in R.

Apply the abs() function to a number

Let’s apply the abs() function directly to a positive and a negative number of the same magnitude, for example, 5 and -5, and compare the output.

# absolute value of a positive number
print(abs(5))
# absolute value of a negative number
print(abs(-5))

Output:

[1] 5
[1] 5

We get the absolute value (5, in this example) without any sign in both cases.

Apply the abs() function to a numeric vector

You can similarly apply the abs() function to a vector in R. Note that individual values in R can be regarded as a vector of length one. If you apply the abs() function to a numeric vector, it will compute the absolute value for each value in the vector.

Let’s look at an example.

# absolute value of a vector
vec <- c(1, -2, 3, -4, -5)
print(abs(vec))

Output:

[1] 1 2 3 4 5

You can see that we get a vector with absolute values for each value in the passed vector. The positive values are unchanged whereas for the negative values we get the corresponding absolute value (without the sign).

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.