0

My data looks like this:

library(tidyverse)
df <- tibble(
    x_val = c(10.3, 14.3, 18.7)
)

After passing each x_val to my_fun...

my_fun <- function(x) {
    x * pi
}

df %>% rowwise() %>% mutate(y_val = my_fun(x_val))

...I get the following:

# A tibble: 3 × 2
x_val    y_val
<dbl>    <dbl>
1  10.3 32.35840
2  14.3 44.92477
3  18.7 58.74778

How might I reverse the function (without just dividing by pi! because my actual function is a lot more complex) to find the appropriate value of x_val to get y_val that is the nearest integer - 0.01 .. to achieve x.99:

32.99
44.99
58.99
emehex
  • 9,874
  • 10
  • 54
  • 100
  • 1
    Try `df %>% mutate(y_val = trunc(my_fun(x_val)) + 0.99)` – akrun Oct 26 '16 at 15:33
  • 1
    Alternatively you could add `ceiling(x) - .01` to your function. – Zach Oct 26 '16 at 15:34
  • Sorry, I should have been more clear... I need to know the correct value of `x_val` to get 32.99 .... (10.501) .... without simply dividing by pi (because my actual function is a lot more complex – emehex Oct 26 '16 at 15:41

1 Answers1

1

From what I understand you have a function f(x_val) that is complex and you want the inverse function of f. You want to find x_val by knowing the y_val. By checking Solving for the inverse of a function in R you could try (adjust the lower and upper parts I do not know the limits of your function):

inverse = function (f, lower = -100, upper = 100) {
  function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]
}

yourfunction_inverse = inverse(my_fun, 0.1, 100)

And the results will be

results <- sapply(c(32.99, 44.99, 58.99), yourfunction_inverse)
Community
  • 1
  • 1
User2321
  • 2,952
  • 23
  • 46