Fixing R Errors -error: unexpected ‘}’ in “}”

While error messages themselves are an unfortunate part of programming, they can be even more annoying when the wording does not show the actual problem. It is even worse is when an error message is confusing. Unfortunately, the ‘error: unexpected ‘}’ in “}”‘ error message is one of these, although once you understand it, it makes some sense. Unfortunately, it is an easy error to make, but it is also easy to fix.

The circumstances of this error.

This error occurs when brackets are not used properly. It usually results from accidentally omitting one or more brackets from your code. Not only is there more than one set of circumstances that produce this error, but some produce other error messages as well.

> x = rep(1, 10)
> for(i in 1:10)
+ if (i > 1)
+ x[i] = x[i] + 1
> }
Error: unexpected ‘}’ in “}”

In his first example, the “{” bracket has been omitted in the for-loop. It also points to one of the reasons this message is hard to understand.

> x = rep(1, 10)
> for(i in 1:10) {
+ if i > 1
Error: unexpected symbol in:
“for(i in 1:10) {
if i”
> x[i] = x[i] + 1
> }
Error: unexpected ‘}’ in “}”

In this case, the parentheses are missing from the logical argument of the if-statement. In this case, it triggers two errors, but one of them is ‘error: unexpected ‘}’ in “}”‘ and so it needed to be mentioned.

What is causing this error?

The cause of this error message is incomplete or missing brackets. This particular version of the error occurs when “}” is isolated on a line but it only occurs when the program encounters it without an opening bracket.

> x = rep(1, 10)
> for(i in 1:10) {
+ if (i > 1)
+ x[i] = x[i] + 1
+ }

This example runs without any error messages. In the first example, there is no opening bracket and so the program was not expecting a closing bracket on that line. In the second example, the error message results from the program being kicked outside an opening bracket by the first error message. With both cases the cause is the same, the program is encountering a closing bracket without an opening bracket.

How to fix this error.

If you are getting this error message following another error message, forget about trying to solve this one because most likely solving the first one will fix this one as well. If however, it occurs by itself, then you are missing an opening bracket someplace. The way to fix it is to look back over your code to see if you have a missing opening bracket someplace. Once you find where it should be, add the bracket and the problem will be fixed.