0

我已经编写了一个函数来计算 BMI 并拥有创建相应图形输出的代码。我的目标是将图形输出包含到函数中,这样我就可以通过使用函数来获得绘图。

我当前的代码:

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")

通过仅修改功能中的米和公斤,我想得到一个具有正确线和点定位的图表。我从下面的代码开始 - 但是它还不起作用。

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)
}
4

1 回答 1

1

你的第二个函数的问题是它产生了无限递归。
如果你像这样改变它,你会得到你想要的:

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
于 2013-10-19T10:32:42.953 回答