Search code examples
rfunctionargumentsparameter-passingstdin

R call function with and without an argument


There's a function I want to call recursively in R. The first time, I don't pass any argument to it, and readLines does the job. So it would be something like this:

func<-function(word){
  if(word doesn't exist){
    word<-readLines(stdin(),n=1)
  }
  ... #function transform word into next_word
  func(next_word)
}

func()

I wonder if that's possible.


Solution

  • One approach would be to set the default of word to NULL:

    func<-function(word = NULL){
      if(is.null(word)){
        word<-readLines(stdin(),n=1)
      }
      #stuff
    }
    

    Then, when you call func and provide an argument, it will be used as the object indicated by the symbol word. If you call it without an argument, word will be the default, NULL, and thus information will be read from stdin.