Conditional Operations Error in R

Asked

Viewed 156 times

3

I am programming a simple recursive algorithm to compute the Fibonacci sequence in R, as I do in C. Follow the same 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 apparently runs 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 interrupted

Could someone help me?

  • I can’t reproduce the error, apparently everything is fine. For safety reasons it might not be a bad idea to have the first instruction of the function stopifnot(n > 0L).

1 answer

4


The function readline does not work well in non-interactive use. From the function documentation itself 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 have passed the value "" which is an empty string. Next 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 function readLines, 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))
  • I did not understand very well the prototype of this "readLines" to fit in this case. Where do I enter the display text to the user in order to enter the input? It is necessary to do the conversion with "as.integer(n)" after such?

  • It seems to me that the error persists.

  • Hi, I edited the answer with the entire script. For me there is no more error... What error appears to you?

  • 2

    You used the cat command to display text, true. I’ve never read keyboard input before with R, now I know how to do it. Thank you so much Daniel, you’ve solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.