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?
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