Unexpected "else" error in "else"

I get this error:

Error: unexpectedly "else" in "else"

From this 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) } } 

What is wrong with this?

+42
r if-statement
Feb 13 '13 at 23:47
source share
2 answers

You need to rearrange the curly braces. Your first statement is complete, so R interprets it as such and generates syntax errors on other lines. Your code should look like this:

 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) } 

Simply put, if you have:

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

Then R reads the first line and, since it is completed, starts the whole line. When he gets to the next line, it will be "Else? Else what?" because it is a completely new statement. In order for R to interpret else as part of the previous if statement, you must have curly braces to tell R that you have not finished:

 if(condition == TRUE) {x <- TRUE } else {x <- FALSE} 
+66
Feb 13
source share

I would suggest reading the syntax a bit. 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) 
+6
Feb 13 '13 at 23:51
source share



All Articles