One common error you may encounter in R is:
Error: unexpected string constant in...
This error occurs when you use quotation marks in an incorrect place in R.
The following three examples illustrate when this error can occur in different scenarios.
Example 1: Unexpected String Constant When Importing File
Suppose we attempt to import a colon-delimited file as a data frame in R:
#attempt to import colon-delimited file
read.csv("C:\Users\Bob\data.csv", sep";")
Error: unexpected string constant in "read.csv("C:\Users\Bob\data.csv", sep";""
We receive an error because we forgot to include an equal sign after the sep argument.
If we add an equal sign, we’ll be able to resolve this error:
#import colon-delimited file
read.csv("C:\Users\Bob\data.csv", sep=";")
team points
1 A 4
2 B 9
3 C 9
4 D 8
5 E 6
Example 2: Unexpected String Constant When Viewing Data
Suppose we attempt to view the values in a vector:
#create numeric vector of values
data #attempt to view values
data""
Error: unexpected string constant in "data"""
We receive an error because we accidently included quotations after the vector name.
If we simply remove the quotations we’ll be able to resolve this error:
#create numeric vector of values
data #view values
data
[1] 4 4 5 6 8 10 13 15 19 18
Example 3: Unexpected String Constant When Creating Plots
Suppose we attempt to view the values in a vector:
#create numeric vector of values
data #attempt to create boxplot to visualize distribution of values
boxplot(data, col'steelblue')
Error: unexpected string constant in "boxplot(data, col'steelblue'"
We receive an error because we forgot to include an equal sign after the col argument.
If we simply add an equal sign, we’ll be able to resolve this error:
#create numeric vector of values
data #create boxplot to visualize distribution of values
boxplot(data, col='steelblue')
The unexpected string constant error can occur in many different scenarios, but these three examples illustrate common instances when it can occur.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix: (list) object cannot be coerced to type ‘double’
How to Fix in R: invalid model formula in ExtractVars
How to Fix in R: replacement has length zero