I am trying to write an ifelse statement that looks at the observations of variable3 and variable4 and returns the values for a new variable5. If the value of variable4 is greater than the value of variable 3, I want the value of variable5 to be (variable4 / variable3) %*% -1. If the value of variable4 is less than the value of variable 3, I want variable 5 to be (variable3 / variable4). Any help would be greatly appreciated!
CodePudding user response:
Ifelse looks like this: condition, valueIfTrue, valueIfFalse, so:
variable5 = ifelse(variable4 > variable3, (variable4 / variable3) %% 1, variable3 / variable4)
CodePudding user response:
Here is a vectorized way.
variable3 <- c(111, 278, 79, 222)
variable4 <- c(179, 201, 55, 178)
df1 <- data.frame(variable3, variable4)
df1$variable5 <- with(df1, pmax(variable3, variable4)/pmin(variable3, variable4))
df1$variable5 <- df1$variable5 * (2*(df1$variable3 > df1$variable4) - 1)
df1
#> variable3 variable4 variable5
#> 1 111 179 -1.612613
#> 2 278 201 1.383085
#> 3 79 55 1.436364
#> 4 222 178 1.247191
Created on 2022-09-22 with reprex v2.0.2