Error in Conditional Operations in Language R

3

I am programming a simple recursive algorithm to calculate the Fibonacci sequence in R, just as I do in C. It follows the same thing below:

fibonacci <- function (n)
{
  if (n == 1L)
    return (0L)
  else if (n == 2L || n == 3L)
    return (1L)
  else
    return (fibonacci(n - 1L) + fibonacci(n - 2L))
} 

n <- readline(prompt="Insira um valor inteiro: ")
n <- as.integer(n)

print(fibonacci(n))

The script seems to run smoothly in the RStudio environment. But when running on the linux console, I get the following error:

  

Enter an integer value:   Error in if (n == 1L) return (0L) else if (n == 2L || n == 3L) return (1L) else return (fibonacci (n -     missing value where TRUE / FALSE required   Calls: print - > fibonacci   Execution stopped

Could anyone help me?

    
asked by anonymous 22.09.2018 / 15:34

1 answer

4

The readline function does not work right in non-interactive use. From the function's own documentation we read:

  

In non-interactive use the result is as if the response was RETURN and   the value is "".

That is, in non-interactive use, it is as if you had passed the value "" which is an empty string. Then you do as.integer("") which results in NA - so the comparison gives problem.

In non-interactive use (calling from the console) you can use the readLines function, as follows:

n <- readLines("stdin",n=1)

The complete script would look like this:

fibonacci <- function (n)
{
  if (n == 1L)
    return (0L)
  else if (n == 2L || n == 3L)
    return (1L)
  else
    return (fibonacci(n - 1L) + fibonacci(n - 2L))
} 

cat("Insira um valor inteiro: \n")
n <- readLines("stdin",n=1)
n <- as.integer(n)

print(fibonacci(n))
    
22.09.2018 / 17:48