user7170429
user7170429

Reputation:

Why getting argument is of length zero` in R?

I have a simple function called PAP. I'm wondering when I run it why I get the following error:

Error in if (n.sim < 2) { : argument is of length zero

Here is my PAP function:

PAP = function (n.sim, sim.time){

   n.sim = if(n.sim < 1) { n.sim = 1 } # If a user put zero or a negative number, make it 1
sim.time = if(n.sim < 2) { sim.time = 0 } else { sim.time } 

for (i in 1:n.sim) {

  plot( rnorm(1e2) )

 Sys.sleep( sim.time ) }
}

PAP(n.sim = 2, sim.time = 5)

Upvotes: 0

Views: 994

Answers (1)

Marius
Marius

Reputation: 60180

You shouldn't try to assign the results of an if statement, because this happens:

> n.sim = 2
> n.sim = if(n.sim < 1) { n.sim = 1 }
> n.sim
NULL

Instead you should do:

PAP = function (n.sim, sim.time){

    if(n.sim < 1) { 
        n.sim = 1 
    } # If a user put zero or a negative number, make it 1
    if(n.sim < 2) { 
        sim.time = 0 
    } # else didn't do anything here so removed

    for (i in 1:n.sim) {

        plot( rnorm(1e2) )

        Sys.sleep( sim.time ) 
    }
}

i.e. just use if as a control flow statement that determines whether particular lines get executed, and use the code within the if statement to change your variables.

Upvotes: 4

Related Questions