How to Solve R Error: unexpected ‘}’ in “}”

by | Programming, R, Tips

This error occurs when you have a closing curly bracket in your code without a corresponding opening curly bracket. You can solve this error by finding the position in your code that requires an opening bracket.

This tutorial will go through how to solve the error with code examples.


Table of contents

Example

Let’s look at an example to reproduce the error:

# Define a vector
x = c(1:10)

# Define a for loop over vector and square each element
for (i in 1: 10) 

x[i] = x[i] ** 2

}

# Print vector to console

x

Let’s run the code to see what happens:

Error: unexpected '}' in "}"

The error occurs because the for loop has a closing bracket but not an opening bracket.

Solution

We can solve the error by ensuring we use an opening bracket. The syntax for a for loop in R is:

for (val in sequence) 
{
  statement
}

Let’s look at the revised code:

# Define a vector

x = c(1:10)

# Use an opening curly bracket for for loop

for (i in 1: 10) {
  x[i] = x[i] ** 2

}

# Print vector to console

x

Let’s run the code to get the result:

 [1]   1   4   9  16  25  36  49  64  81 100

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun, and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee