R if-else not working

What is wrong with this if-else in my R program?

if(is.na(result)[1]) print("NA") else coef(result)[[1]] 

I get an error message:

 > if(is.na(result)[1]) + print("NA") > else Error: unexpected 'else' in "else" > coef(result)[[1]] 

So, I added braces around if and else, and now I get this error:

 > if(is.na(result)[1]) { +   print("NA") Error: unexpected input in: "if(is.na(result)[1]) { ¬" > } else { Error: unexpected '}' in "}" >   coef(result)[[1]] Error: unexpected input in "¬" > } Error: unexpected '}' in "}" 
+6
source share
5 answers

This is what you lack in braces. Try

 if(is.na(result)[1]) { print("NA") } else { coef(result)[[1]] } 

This is not the case when the source has the whole file at once, but for linear parsing (for example, when you enter the prompt) you must tell R that more code is coming.

+22
source

I think your problem is signaled by this error message:

 "if(is.na(result)[1]) { ¬" 

Notice that weird little character? You received a non-printable character that looks like one of these old IBM end markers. This could be a problem with your LOCALE lines or with a keyboard display or code that you have logged off the Internet. It's hard to say, but you must definitely try to get rid of them by contacting them /

+8
source

Without curly braces, the if ... else ... should only be on one line:

 if(is.na(result)[1]) print("NA") else coef(result)[[1]] 
+4
source

If you have only one condition and two results, it is syntactically easier to use ifelse()

 ifelse(is.na(result)[1], print("NA"), coef(result)[[1]] ) 
+2
source

This runs for me without errors

 x <- 1:5 result <- lm(c(1:3,7,6) ~ x) if(is.na(result)[1]) { print("NA") } else { coef(result)[[1]] } 

and produces

 [1] -0.7 
0
source

Source: https://habr.com/ru/post/894227/


All Articles