[英]function as an argument of a function in R
我具有已保存在数据库中的此功能。
runifrect <- function(n,a,b,z,d) {
else(print("Check if the x and y coordinates lie as such: 0<=a<b<=1 and 0<=z<d<=1"))}
现在,我尝试使用旧的方法来定义此功能:
plotrectpoints<- function(runifrect(n,a,b,z,d),a,b,z,d) {
但是我遇到一个错误,我不明白该函数出了什么问题,我希望它对任意值n,a,b,z,d起作用。
当在R中定义一个函数时,它无法评估括号中的值。 而是创建伪对象,该伪对象在调用函数时获取值。 这些伪对象名称遵循应用于所有变量名称的相同规则。 由于不能在括号中包含变量名,因此在定义函数时不能将其包括在参数列表中。
第一功能定义
runifrect <- function(n,a,b,z,d) {
if(a<1&a>=0&b>0&b<=1&z<1&z>=0&d<=1&d>0) {
x <- runif(n,a,b)
y <- runif(n,z,d)
k<-c(x,y)
matrix(k,nrow = n,ncol = 2)}
else(print("Check if the x and y coordinates lie as such: 0<=a<b<=1 and 0<=z<d<=1"))}
第二功能定义
plotrectpoints<- function(x,a,b,z,d) {
plot(x,
xlim=c(0,1),
ylim=c(0,1),
main = "Plot of rectangle and randomly generated points")
rect(a,z,b,d, border='red',lty='dotted')}
调用函数
plotrectpoints( runifrect(n,a,b,z,d), a,b,z,d)
这是我在该平台上的第一个答案。 请多多包涵。
如果您的最终目标是从“ plotrectpoints()”函数中调用“ runifrect()”函数,则可以删除“ runifrect(n,a,b,z,d)”参数,并将其替换为“ n”。 该代码应如下所示:
runifrect <- function(n,a,b,z,d) {
if(a<1&a>=0&b>0&b<=1&z<1&z>=0&d<=1&d>0) {
x <- runif(n,a,b)
y <- runif(n,z,d)
k<-c(x,y)
matrix(k,nrow = n,ncol = 2)}
else(print("Check if the x and y coordinates lie as such: 0<=a<b<=1 and 0<=z<d<=1"))}
plotrectpoints<- function(n,a,b,z,d) {
plot(runifrect(n,a,b,z,d),
xlim=c(0,1),
ylim=c(0,1),
main = "Plot of rectangle and randomly generated points")
rect(a,z,b,d, border='red',lty='dotted')}
并且我使用以下参数进行测试。
plotrectpoints(10,0.5,0.8,0.3,0.7)
我还附上了上面生成的代码图。 在此处输入图片说明。如果上面的代码正是您要寻找的,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.