Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating how many increments larger one value is compared to another

I have some incremental numerical data that has a specific range of values, where all increments is the double of the previous value, e.g. 0.064, 0.128, 0.256, 0.512, 1.024 ...
I want to calculate how many increments higher a specific value is to another. Based on this value I want to define that if this incremental change is equal to or larger than 3, the test value is TRUE. I cannot base this directly on the numerical value, as this will not reflect the incremental changes, e.g. the value 64 here would be 8 increments higher than 0.25, and not 256, as it would be if the actual numeric value was used.

library(dplyr)

testdata <- data.frame(
  var1 = c(0.25, 0.5, 2, 64, 32),
  var2 = c(0.064, 64, 32, 16, 0.128)
)



testdata %>%
  mutate(
    test = case_when(
      var1/var2 >= 3 ~ TRUE,
      TRUE ~ FALSE
    )
  )

Any ideas on how this could be done?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you want is the base 2 logarithm of the division between your two numbers. For instance, 64 / 0.25 = 256 = 2^8.
In R, you can use log to do that:

f <- function(x1, x2) log(x1 / x2, base = 2)
f(64, 0.25)
#[1] 8

With your data:

transform(testdata, test = f(var1, var2) >= 3)
#    var1   var2  test
# 1  0.25  0.064 FALSE
# 2  0.50 64.000 FALSE
# 3  2.00 32.000 FALSE
# 4 64.00 16.000 FALSE
# 5 32.00  0.128  TRUE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading