How to replace variables with NEGATIVE values with their ABSOLUTE VALUE within a date.frame in R?

Asked

Viewed 309 times

3

First of all, what is an Absolute Value?

We can say that the Absolute Value or Module is the same as the distance from a real number to zero, because the module of a real number arose from the need to measure the distance from a negative number to zero. When we measure the distance of any negative number to zero, we realize that the distance becomes negative and as it is not usual to say that a distance or length is negative has been created the real number module that makes the value positive or zero.

Thus, we can say that the module of a real number will follow two conditions:

• The module or absolute value of a real number is the number itself, if it is positive.

• The module or absolute value of a real number will be its symmetric if it is negative.

The Absolute Value is represented by parallel bars and is calculated as follows. Example:

x = |-5| + |-7|

x = √(-5²) + √(-7²)

x = √25 + √49

x = 5 + 7

x = 12

Now that we know what it is and how to calculate the Absolute Value, let us return to the problem applied in R.

Let’s say I have a 6x5 data.frame, for example:

print(Dados)

Linha  A   B   C   D   E
L1     4   3  -1   2   4
L2     1  -2   1  -5   1
L3    -1  -1   2   3   4
L4     2   4   5  -7   9

But I need to replace the Negative values of the data.frame by the Absolute Value, example:

Linha  A   B   C   D   E
L1     4   3   1   2   4
L2     1   2   1   5   1
L3     1   1   2   3   4
L4     2   4   5   7   9

How can I replace variables with NEGATIVE values with ABSOLUTE VALUE within my date.?

Dice:

Dados <- read.table(text = "
Linha  A   B   C   D   E
L1     4   3  -1   2   4
L2     1  -2   1  -5   1
L3    -1  -1   2   3   4
L4     2   4   5  -7   9
", header = TRUE)

3 answers

7


Using the function abs:

library(dplyr)

Dados %>%
  mutate_if(is.numeric, abs)
##   Linha A B C D E
## 1    L1 4 3 1 2 4
## 2    L2 1 2 1 5 1
## 3    L3 1 1 2 3 4
## 4    L4 2 4 5 7 9
  • You were faster than me. I’m going to erase mine, hahaha. Best solution is that same.

  • Hahaha happens : )

  • Thank you for the reply Marcus Nunes e neves. I will test.

3

Use the function abs (Absolute value). Since the module (absolute value) can only be calculated on numbers, the most coherent solution is to analyze by the classes of vectors present in Dados.

Assuming you want to parse vectors of integer numbers (which is your case), you can use the function rapply, of R base, which dispenses with the use of additional packages:

rapply(object = Dados, classes = 'integer', how = 'replace', f = abs)

  Linha A B C D E
1    L1 4 3 1 2 4
2    L2 1 2 1 5 1
3    L3 1 1 2 3 4
4    L4 2 4 5 7 9

-1

  • 3

    This doesn’t work because of Dados have a factor.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.