开发者

R if-else not working [duplicate]

This question already has answers here: if/else constructs inside and outside functions (2 answers) Closed 10 years ago.

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

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

I'm getting an error:

> if(is.na(result)[1])
+   print("NA")
> else
Error: unexpected 'else'开发者_如何学Python in "else"
>   coef(result)[[1]]

So then I added curly braces around the if and the 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 "}"


It is that you are lacking curly braces. Try

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

This matters less when your source an entire file at once but for line-by-line parsing (eg when you enter at the prompt) you have to tell R that more code is coming.


I think your problem is signaled with this error message:

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

Notice that strange little symbol? You have gotten a non-printing character that looks like one of those old IBM end-of-line markers. It could be problem with your LOCALE strings or with your keyboard mapping or with code you got off the Internet. Hard to tell, but you should definitely try to get rid of them by backspacing over them/


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

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


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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜