J.Doe
J.Doe

Reputation: 1

function as an argument of a function in R

I have this function which I have saved in the database.

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

Now I am trying to define this function with the use of the old one:

plotrectpoints<- function(runifrect(n,a,b,z,d),a,b,z,d) {

However I am getting an error I dont understand what is wrong with the function, I want it to work for any arbitrary values n,a,b,z,d.

Upvotes: 0

Views: 53

Answers (2)

myvnsk
myvnsk

Reputation: 1

This is my first answer on this platform. Please bear with me.

If your end goal is to call the 'runifrect()' function from the 'plotrectpoints()' function, we can remove the 'runifrect(n,a,b,z,d)' parameter and replace that with 'n'. The code should look as follows:

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

and I have used the following parameters to test.

plotrectpoints(10,0.5,0.8,0.3,0.7)

I have also attached the plot the above code generated. enter image description herePlease let me know if the above code is what you are looking for.

Upvotes: 0

Katia
Katia

Reputation: 3914

When a function is defined in R it cannot evaluate the values in parenthesis. It rather creates dummy objects which get the values when the function is called. These dummy object names follow the same rules that are applied to all variables names. Since you cannot have a variable name contained parenthesis, you cannot include it into the list of arguments when you define the function.

First function definition

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

Second function definition

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

Call to the function

plotrectpoints( runifrect(n,a,b,z,d), a,b,z,d)

Upvotes: 1

Related Questions