我编写了一个计算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")
只需修改仪表&amp;函数中的kg我希望得到一个具有正确线和点定位的图表。我从下面的代码开始 - 但是它不起作用。
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)
}
答案 0 :(得分: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