Open In App

How to Fix: Unexpected String Constant in R

An unexpected string constant: The compiler produces such an error when we use the quotation marks in the incorrect place in R. The error might occur in the below three different scenarios.

Example 1:  When a file is imported.



Let us consider an example in which we try to import a colon-delimited file as a data frame in R. The sample file taken is Sample-Spreadsheet-10-rows.csv.




# Try to import colon-delimited file
read.csv("C:\\Users\\harshit\\gfg.csv", sep";")

Output:



The R compiler produces the error because we haven’t given the equal to (=) just after the sign sep argument. Let’s add the equal to sign after the sep argument and run the program again:




# Try to import colon-delimited file
read.csv("C:\\Users\\harshit\\gfg.csv", sep=";")

Output:

Example 2: When a data is viewed:

Let us consider an example in which we want to see the values in a vector.




# Create a vector having 10 numeric values in it
vect <- c(12, 8, 15, 16, 4, 7, 1, 5, 9, 18)
  
# Print the values
vect""

Output:

The R compiler produces an error because we mistakenly used quotations just after the vector name.

How to resolve:

We can resolve this error by simply removing the quotations:




# Create a vector having 10 numeric
# values in it
vect <- c(12, 8, 15, 16, 4, 7, 1, 5, 9, 18)
  
# Print the values
vect

Output:

Output

Example 3: While Creating Plots:

Let us consider an example in which we try to visualize the distribution of the values in a vector:




# Create a vector having 10 numeric
# values in it
vect <- c(12, 8, 15, 16, 4, 7, 1, 5, 9, 18)
  
# Trying to create boxplot and visualize 
# the distribution of values
boxplot(vect, col'steelblue'

Output:

The R compiler produces an error because equal to sign is missing after col.

How to resolve:

The error can be resolved by simply adding an equal to sign after the col:




# Create a vector having 10 numeric 
# values in it
vect <- c(12, 8, 15, 16, 4, 7, 1, 5, 9, 18)
  
# Trying to create boxplot and visualize
# the distribution of values
boxplot(vect, col='steelblue'

Output:


Article Tags :