0

I have written a function to calculate the BMI and have the code to create a corresponding graphical output. My goal is to include the graphical output into the function so that I get the plot by just using the function.

My current code:

BMI <- function(meter, kg){
  BMI <- kg/(meter^2)
  return(BMI)
}
BMI(1.8,70)

x <- seq(1.5, 1.9, by = 0.001)
y <- seq(30, 200, by = 0.5)
z <- outer(x, y, FUN = function(x, y) {BMI(x, y)})
contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
abline(h = 70, v=1.8, col="darkgrey") 
points(1.8,70, col="red", cex=2, pch=16, bg="red")

By just modifying the meter & kg in the function I would like to get a diagram with the correct line and point positioning. I started with the code below - however it does not work, yet.

graphicalBMI <- function(meter, kg){
  BMI <- kg/(meter^2)
  x <- seq(1.5, 1.9, by = 0.001)
  y <- seq(30, 200, by = 0.5)
  z <- outer(x, y, FUN = function(x, y) {graphicalBMI(x, y)})
  contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
  abline(h = kg, v= meter, col="darkgrey") 
  points(meter, kg, col="red", cex=2, pch=16, bg="red")
  return(graphicalBMI)
}

1 Answer 1

1

The problem of your second function is that it produces an infinite-recursion.
If you change it like this you'll get what you want:

graphicalBMI <- function(meter, kg, showPlot=TRUE){

  BMI <- kg/(meter^2)

  if(showPlot){
    x <- seq(1.5, 1.9, by = 0.001)
    y <- seq(30, 200, by = 0.5)

    # here we call graphicalBMI by setting showPlot=F to avoid infinite recursion
    z <- outer(x, y, FUN = function(x, y) {graphicalBMI(x, y, FALSE)})
    contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
    abline(h = kg, v= meter, col="darkgrey") 
    points(meter, kg, col="red", cex=2, pch=16, bg="red")
  }
  return(BMI)
}


# usage example:
graphicalBMI(1.8,70) # plot produced

graphicalBMI(1.8,70,FALSE) # no plot produced
Sign up to request clarification or add additional context in comments.

1 Comment

EDIT: Simplified the function removing the inner function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.