1.3 Error messages

Errors are common! Like any language, R syntax, spelling, and punctuation are critical in writing code. When error messages pop up in your console:

  • Read the error message as some are clear and intuitive.

  • Check your code for typos, capitalization, punctuation.

Beyond simple coding mistakes, we’ve found that students frequently encounter two types of errors in this course.

1.3.1 Function not found

Consider the following code and corresponding error message:

  mydata %>% mean(varX)
## Error in mydata %>% mean(varX): could not find function "%>%"

Note the specific reference to a missing function (i.e. “could not find function…”). It usually means you need to load a package. In this case, we forgot to load tidyverse, which defines the pipe operator, %>%.

1.3.2 Object not found

Another common issue is that you’re asking R to search for an object, file, or dataset, that doesn’t exist. Consider the following:

# Load the dog dataset
  dog = read.csv('dogdata.csv')
## Warning in file(file, "rt"): cannot open file
## 'dogdata.csv': No such file or directory
## Error in file(file, "rt"): cannot open the connection

The error message indicates that it cannot find the file (“No such file or directory”). In this case, the dogdata.csv data set isn’t in your project folder. It’s often the case that we downloaded a data set but forgot to move it from, e.g., the Downloads folder to our project folder. So move it, and try again.

# Calculate mean weight
  mean(dog$weight)
## Error in mean(dog$weight): object 'dog' not found

This error message is similar to the one above. R tells you that it cannot locate the object (dataframe, variable, graph, etc) that you want to work on (in this case, an object named dog). Look to see that the object is visible in your Environment window, and either load the missing object (“Oops! Forgot to open the data.”) or correct the spelling (“Right, it’s capitalized: Dog”) before trying again.