函数作为R中函数的参数
我有这个功能,我已经保存在数据库中函数作为R中函数的参数,r,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)
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中定义时,它不能计算括号中的值。而是创建虚拟对象,在调用函数时获取值。这些虚拟对象名称遵循应用于所有变量名称的相同规则。由于变量名不能包含括号,因此在定义函数时不能将其包含在参数列表中 第一函数定义
这是我在这个平台上的第一个答案。请容忍我 如果您的最终目标是从“plotrectpoints”函数调用“runifrect”函数,我们可以删除“runifrectn,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')}
我还附上了上述代码生成的绘图。
请让我知道,如果上述代码是你正在寻找的 你能提供一些你看到的错误的细节吗?谢谢。这个错误也没有意义,一个是缺少括号,另一个是找不到对象“a”。我不想在plotrectpoints函数中输入“n”。runifrect的结果将是一个向量,我想在plotrectpoints函数中使用它作为输入参数。在这种情况下,@Katia的答案非常有意义。
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)
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)