Home > Mobile >  Calculation using if_else statement
Calculation using if_else statement

Time:11-18

Is it possible to use mutate and if_else to make calculations? Or is there another function used for that? Example below.

structure(list(X = 1:6, x = c(-50.1298257841559, -49.9523708108406, 
-49.8600298829818, -49.8590735594872, -49.8600022102151, -49.680556540172
), y = c(-29.2498490060132, -29.1594734717135, -29.0700140387022, 
-28.9795033961473, -28.8900003372153, -28.8945716273705), ua = c(1L, 
4L, 10L, 15L, 21L, 23L), species = c(42L, 80L, 48L, 84L, 84L, 
47L), region = c("FOD", "FOD", "FOD", "FOD", "FOD", "FOD"), diff = c(8L, 
6L, 3L, 11L, 13L, 4L), status = c("Ganho", "Ganho", "Ganho", 
"Ganho", "Perda", "Perda")), row.names = c(NA, 6L), class = "data.frame")

What I'm trying to do is when status == "Perda", multiply the column diff by negative 1

Doing

data <- data %>% mutate(diff = if_else(diff > 0, diff, -1 * diff))

Returns that ''the false statement must be an integer vector, not a double vector.''

So, I guess if_else is not the right function for mutating my data. What could I use? Or, if if_else is usable, how can I use it?

CodePudding user response:

if_else checks that both the returns (TRUE or FALSE) are of the same type, since diff is a integer, when you multiple by -1 it is considered a double.

So you can either use ifelse, that does not check it

data %>% mutate(diff = ifelse(diff > 4, diff, -1 * diff))

Or you can use 1L in the multiplication to make a integer

data %>% mutate(diff = if_else(diff > 0, diff, -1L * diff))
  • Related