[SOLVED] My function in r doesn't work. Do you know why?

Issue

find_value <-function(function_2, x)
  {
  x<-readline(prompt = "Enter a real number ")
  function_2<-readline(prompt="Enter a function")
 x<-as.numeric(x)
 function_2<-as.function(function_2)
 return(function_2(x))
}

the function should find the value of a math function for a real number

Solution

as.function is not working as expected. You could use get.

find_value <-function(function_2, x) {
  x <- readline(prompt = "Enter a real number ")
  function_2 <- readline(prompt="Enter a function")
  
  x <- as.numeric(x)
  function_2 <- get(function_2, mode = "function")
  
  return(function_2(x))
}

Or a better alternativ is match.fun as suggested in the comments:

find_value <- function(function_2 = NULL, x = NULL) {
  
  if(is.null(x)) x <- readline(prompt = "Enter a real number ")
  if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
  
  x <- as.numeric(x)
  function_2 <- match.fun(function_2)
  
  return(function_2(x))
}

We could further add checks, whether the arguments are supplied, so we can run the function without argument. In this case it will ask us for input, or we supply the args and the function will just return the calculated value.

find_value <-function(function_2 = NULL, x = NULL) {
  
  if(is.null(x)) x <- readline(prompt = "Enter a real number ")
  if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
  
  x <- as.numeric(x)
  function_2 <- match.fun(function_2)
  
  return(function_2(x))
}

find_value("sqrt", 4)
#> [1] 2

Created on 2022-01-22 by the reprex package (v0.3.0)

We could also use rlang::as_function which supports purrr-like lambda functions as well:

find_value <-function(function_2 = NULL, x = NULL) {
  
  if(is.null(x)) x <- readline(prompt = "Enter a real number ")
  if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
  
  x <- as.numeric(x)
  function_2 <- rlang::as_function(function_2)
  
  return(function_2(x))
}

find_value(~ .x^2, 4)
#> [1] 16

Created on 2022-01-22 by the reprex package (v0.3.0)

Answered By – TimTeaFan

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.