# When running code in R was given an error that there was a missing value where true/false needed and I can't fix it

1467 views
8

I am new to using R and have minimal amount of Python experience. I am sure this is an easy fix but I am just not seeing it. I was given a code to run a Fibonacci sequence to 100 and I copy and pasted it, but I am getting the following error code: Error in if (numterms <= 0) { : missing value where TRUE/FALSE needed. I know this has to do with the if/else clause but I am not seeing the problem. I have run through the code a couple different ways but it has not helped. And the person to assist is not available during the weekend. Any help would be appreciated.

``````# take the max number input from the user

# first two items
num1 = 0
num2 = 1
counter = 2

# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an  integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci  sequence:")
print(num1)
} else {
print("The Fibonacci  sequence:")
print(num1)
print(num2)
while(counter <  numterms) {
numth = num1 + num2
print(numth)
# update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
``````

2

If you just execute the code `numterms` is not correctly defined. It is normally defined by a user input: The function readline reads the numbers the user types in the command line. If you just execute this line you can properly define `numterms`.

If you execute all the code at once `numterms` is set to `NA` which cannot be compared to `0` in the `numterms <= 0` clause. In this case `numterms <= 0` is also `NA` which is not a logical value and can therefore not be evaluated by `if`. This ultimately causes your error.

The solution would be to just run the first line of your code and enter the number and only after you entered the number to execute the rest of the code.

Alternatively you can define your code as a function:

``````printFibonacci <- function(){

if(is.na(numterms)){
numterms <- 4
}

# first two items
num1 = 0
num2 = 1
counter = 2

# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an  integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci  sequence:")
print(num1)
} else {
print("The Fibonacci  sequence:")
print(num1)
print(num2)
while(counter <  numterms) {
numth = num1 + num2
print(numth)
#  update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
}
``````

And then just call your function with `printFibonacci()`. In this case the prompt and answer of the `readline` function gets executed first and `numterms` can be defined by the user before the rest of the code is executed.

posted this