Error: Unexpected Symbol/Input/String Constant/Numeric Constant/Special in My Code

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

Getting unexpected input error in R expression

As noticed in the SO thread Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code :

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.

Most probably, here this is due to the symbol ˆ you are using, which is not the appropriate one for an exponent ^:

# correct symbol ^:
> 2^2
[1] 4

# wrong symbol you seem to use ˆ :
> 2ˆ2
Error: unexpected input in "2ˆ"

Change it to the correct one ^ and you will be fine.

R Error: unexpected '}' in }

Your code has a number of issues:

  1. The if statement would need enclosing {} symbols.
  2. The if also needs enclosing () symbols around the logical expression.
  3. The result of the recode function is not stored anywhere (the function does not change values-in-place).
  4. Loops are a poor solution to this problem.

It would be much simpler to take advantage of R's natural vectorization. Rather than an if inside a for loop, you can this all in one line:

data$terminate_reason[data$terminate_reason == '(Null Value)'] <- NA

That should do the trick, but ensure that the "terminate_reason" column is character, not factor.

Error: unexpected '}' in } in R

It seems you using unicode characters in your code: ”p =”,p).

Replace

hist(x,prob=T,breaks=20,main=paste("n =",n,”p =”,p))

by

hist(x,prob=T,breaks=20,main=paste("n =",n, "p =",p))

unexpected numeric constant in: ggplot(

I still can't get your code above to run because it's missing all the single-letter variables and I don't want to define those manually so I can't reproduce the error.

But a better way to plot your data would be to melt it first.

library(reshape2)
mm<-melt(AGEgroups, id.vars="Year")

then plot with

ggplot(mm,aes(x=Year, y=value, fill=variable)) +
geom_area() + ylab("Number of Applicants") +
scale_fill_hue(name = "Age Range",
labels=c(paste(17:24, "yrs"),"25 to 29", "30 to 39", "40+"))

which produces

Sample Image

Here we clearly label the plot using the more standard assignments rather than relying on the side effects of using imaginary variables in the aesthetics. This make this intention of the code much clearer.

Nested IF function in R

You are using assignments in your if conditions instead of equality checks. In addition, you need to preface every if in a chain, other than the first one, with else. Try this code:

my_function <- function(x, display = FALSE, type) {
if (display == TRUE & type == "hist") {
hist(x)
} else if (display == TRUE & type == "plot") {
plot(x)
} else {
summary(x)
}
}


Related Topics



Leave a reply



Submit