 # The abs() Function In R: How To Use abs() In R 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:

 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:

  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:

Posted in R