Hello,
I am doing a simple if else statement in R. But it always comes out error
such as 'unexpected error'
There are two variables. ini and b. when ini=1, a=3; when ini>1 and b>2,
a=5; all other situations, a=6. I don't know where it is wrong.
Here is my code
ini=3
b=4
if (ini==1) {
a=3
}
else if (ini>1 and b>2 ) {
a=5
}
else {a=6}
Thanks a lot.
--
Best,
Chen
[[alternative HTML version deleted]]
align the 'else if' and 'else' with the closing curly brackets.
if (condA){
doStuff()
} else if (condB){
doOtherStuff()
} else {
doWhatever()
}
b
On Oct 3, 2009, at 12:54 PM, Chen Gu wrote:
> Hello,
>
> I am doing a simple if else statement in R. But it always comes out
> error
> such as 'unexpected error'
> There are two variables. ini and b. when ini=1, a=3; when ini>1 and
> b>2,
> a=5; all other situations, a=6. I don't know where it is wrong.
> Here is my code
>
> ini=3
> b=4
> if (ini==1) {
> a=3
> }
> else if (ini>1 and b>2 ) {
> a=5
> }
> else {a=6}
>
>
> Thanks a lot.
> --
> Best,
> Chen
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
On Oct 3, 2009, at 11:54 AM, Chen Gu wrote:> Hello, > > I am doing a simple if else statement in R. But it always comes out > error > such as 'unexpected error' > There are two variables. ini and b. when ini=1, a=3; when ini>1 and > b>2, > a=5; all other situations, a=6. I don't know where it is wrong. > Here is my code > > ini=3 > b=4Your basic problem is that you are confusing if and else which are program control functions with ifelse which is designed for assignment purposes; > ini=3 > b=4 > a <- ifelse( ini==1, 3, ifelse( ini>1 & b>2 , 5, 6)) > > a [1] 5> if (ini==1) { > a=3 > } > else if (ini>1 and b>2 ) {The error is probably being thrown because "and" is not a valid conjunction operator in R. > 1 and 1 Error: syntax error > 1 & 1 [1] TRUE> a=5 > } > else {a=6} > > e.David Winsemius, MD Heritage Laboratories West Hartford, CT
On 03/10/2009 11:54 AM, Chen Gu wrote:> Hello, > > I am doing a simple if else statement in R. But it always comes out error > such as 'unexpected error' > There are two variables. ini and b. when ini=1, a=3; when ini>1 and b>2, > a=5; all other situations, a=6. I don't know where it is wrong. > Here is my code > > ini=3 > b=4 > if (ini==1) { > a=3 > }The statement above is complete, so it will be evaluated.> else if (ini>1 and b>2 ) {Then R sees the else, which can't start a new statement, and signals an error. Put the else on the same line as the previous closing brace and things will be fine. Duncan Murdoch> a=5 > } > else {a=6} > > > Thanks a lot.