2013-02-13 59 views
43

我得到这个错误:意外的 '其他' 中的 “其他” 错误

Error: unexpected 'else' in " else"

从这if, else声明:

if (dsnt<0.05) { 
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) } 
else { 
     if (dst<0.05) { 
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) } 
    else { 
     t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)  } } 

有什么不对呢?

+2

您的if语句在第二行完成。将大括号移动到第三行的开头。为第五名做同样的事情。 – 2013-02-13 23:50:43

+1

可能重复的http://stackoverflow.com/questions/13724063/if-else-constructs-inside-and-outside-functions – 2013-02-14 10:49:20

回答

6

我建议阅读一下语法。 See here.

if (dsnt<0.05) { 
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) { 
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else 
    t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
+0

正当我想我应该添加重写的代码很好,我意识到答案已经已被sebastian-c回答.. – nadizan 2013-02-14 00:07:01

+1

对不起。不过,我很欣赏链接到语言定义。它确实回答了这个问题。 – 2013-02-14 00:17:08

67

您需要重新排列大括号。你的第一个陈述是完整的,所以R解释它,并在其他行上产生语法错误。你的代码应该是这样的:

if (dsnt<0.05) { 
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) { 
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else { 
    t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)  
} 

要说得简单些,如果您有:

if(condition == TRUE) x <- TRUE 
else x <- FALSE 

则R读取第一行,因为它是完整的,运行在其全部。当它到达下一行时,它会变成“其他?否则呢?”因为这是一个全新的说法。要让R将else解释为前面if语句的一部分,必须使用大括号来告诉R您尚未完成:

if(condition == TRUE) {x <- TRUE 
} else {x <- FALSE}