Home > Software design >  Calculate Numerator and determinator in Mutate R
Calculate Numerator and determinator in Mutate R

Time:12-11

I have this table for example in R:

A10 B100
-3 0
0 1
0 1
2 -4

And I have 10,000 of this row.

I am trying to compute:

df$Result = (GREATEST(1,[A10] 1)) / (GREATEST(1,[B100] 1)) 

For the numerator: (GREATEST(1,[A10] 1))

If [A10] 1 is less than 1, then you should use 1 for the numerator, else use [A10] 1.

For the denominator: (GREATEST(1,[B100] 1))

If [B100] 1 is less than 1, then you should use 1 for the denominator else use [B100] 1.

How do I code this mutate R? There are over 10 combinations.

CodePudding user response:

You can use pmax to get (GREATEST(1,[A10] 1)) and the same for denominator/

library(dplyr)

df <- df %>% mutate(result = pmax(1, A10   1) / pmax(1, B100   1))
df

#  A10 B100 result
#1  -3    0    1.0
#2   0    1    0.5
#3   0    1    0.5
#4   2   -4    3.0

CodePudding user response:

Another way to get this problem done would be using ifelse() function as follows

library(dplyr)

df <- df %>%
        mutate(result = (ifelse(1 > A10   1, 1, A10  1))/(ifelse(1 > B100   1, 1, B100  1)))

  •  Tags:  
  • r
  • Related