Search code examples
rfunctioncallsequential

function call and execution in R


I have 2 functions defined one after the other. When I call them as a block the 1st function is executed (will become clear when you see below and I understand whats happening here and why it's happening) and the second function call gets ignored. Can this be fixed ?

Apologies if this is a repeat question. Can't seem to find the solution for this.

mini_val<-function()
{
  m <- readline("Minimum: ")
  if(!grepl("^[0-9]+$",m))
  {
    return(mini_val())
  }
  return(as.integer(m))
}

mini<-mini_val()

max_val<-function()
{
  m <- readline("Maximum: ")
  ifelse(!grepl("^[0-9]+$",m),return(max_val()),ifelse(m>=mini,as.integer(m),return(max_val()))) 
  return(as.integer(m))
}

maxi<-max_val()

when I run the entire block, the following happens:

 mini<-mini_val()
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   max_val<-function()
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   {
Minimum number of segments (between 3 and 20) or Hit ESC to exit:     m <- readline("Maximum number of segments (between 3 and 20) or Hit ESC to exit: ")
Minimum number of segments (between 3 and 20) or Hit ESC to exit:     ifelse(!grepl("^[0-9]+$",m),return(max_val()),ifelse(m>=mini,as.integer(m),return(max_val()))) 
Minimum number of segments (between 3 and 20) or Hit ESC to exit:     return(as.integer(m))
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   }
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   
Minimum number of segments (between 3 and 20) or Hit ESC to exit:   maxi<-max_val()
Minimum number of segments (between 3 and 20) or Hit ESC to exit: 1
> 

Any idea how I can get around this ?

Thanks!, LR.


Solution

  • The second function gets ignored because your program is still taking in readline("Minimum: ") input from the command line. You'll need to give it a numeric response first to proceed with your code.

    For instance, you could just add a line with nothing but 4 after the mini_val() line, and it will work when you run them in a block:

    ...
    }
    
    mini<-mini_val()
    4
    
    max_val<-function()
    {
    ...
    

    Though this will not be very useful, since it's the same as running mini <- 4.

    To produce the behavior you want, you need to run this in a .R file with source("yourfile.R"), rather than on the command line. (Presumably you were either copy-pasting it into R, or running it in RStudio by selecting all, or a similar procedure for running it line-by-line). When you source it from a file, you get the desired behavior:

    > source("yourfile.R")
    Minimum: 2
    Maximum: 3