parse in geom_label : ERROR while rich displaying an object: Error in parse(text = text[[i]])=
Study help("plotmath")
.
library(ggplot2)
ggplot()+
geom_label(aes(x = 10, y = 0.545,
label = " expression 1 = p-value = 9.19 e-09 ; CI : [0.00, 0.00]"),
label.size = NA , hjust =0.08, size = 3.5)+
geom_label(aes(x = 10, y = 0.509,
label = paste("'expression 2 = ' * italic(p) * '-value = 9.19 e-09 ; CI : [0.00, 0.00]'")),
label.size = NA, hjust =0.08, size = 3.5, parse = T)
I have removed family = "Helvetica"
because it caused warnings on my system.
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
R parse with bracket
I don't know what NAFC_page
is, but one way to attack this problem is to replace the parse
with cat
and then look at it with code-highlighting (such as using SO's lang-r
engine).
cat("NAFC_page(label=\"quiet_question\", prompt=\"htmltools::HTML('<p>Are you in a quiet environment?</p>'), choices = \"c(Yes, No)\", \", save_answer = FALSE )", "\n")
Since the output this produces is typically a single line requiring horizontal-scrolling, I'm going to interject two newlines to try to keep it all visible in a "normal" browser screen (not necessarily mobile-aware, sorry). This produces:
NAFC_page(label="quiet_question",
prompt="htmltools::HTML('<p>Are you in a quiet environment?</p>'),
choices = "c(Yes, No)", ", save_answer = FALSE )
Using SO's code highlighting, the first thing that stands out to me is that htmltools::HTML
is marked as a string. Let's remove the \"
before it and see what else we see. (cat
'ed again, just showing the output.)
NAFC_page(label="quiet_question",
prompt=htmltools::HTML('<p>Are you in a quiet environment?</p>'),
choices = "c(Yes, No)", ", save_answer = FALSE )
Okay, now I see that \"c(Yes, No)\"
is marked as a string, where I would normally expect it to be a vector c("Yes", "No")
. Again:
NAFC_page(label="quiet_question",
prompt=htmltools::HTML('<p>Are you in a quiet environment?</p>'),
choices = c("Yes", "No"), ", save_answer = FALSE )
Now we see that the last argument save_answer=
(and the rest of the line, in fact) is a string. Let's remove the random quote-comma we see there:
NAFC_page(label="quiet_question",
prompt=htmltools::HTML('<p>Are you in a quiet environment?</p>'),
choices = c("Yes", "No"), save_answer = FALSE )
That looks much nicer, and likely parses/evaluates better, too.
From here, we should be able to put that back in to your parse
call:
parse(text="NAFC_page(label=\"quiet_question\", prompt=htmltools::HTML('<p>Are you in a quiet environment?</p>'), choices = c(\"Yes\", \"No\"), save_answer = FALSE )")
In case the syntax-highlighting portion SO uses changes, here are screenshots for each stage, in order.
unexpected symbol in R please see the code
you have your whole function in one physical line.
Therefore, when R
tries to parse it, it has no way of knowing when one line ends and the next one begins.
To fix this, either use separate lines or add a semicolon between them.
Alternatively, you can have the formatR
package do it for you!
(pretty awesome package):
install.packages("formatR")
library(formatR)
tidy.source("mySource.R", reindent.space=5)
aggall = function(df, grp) {
numcols = sapply(df, class) %in% c("integer", "numeric")
result = aggregate(df[, numcols], df[grp], mean)
counts = as.data.frame(table(df[grp]))
names(counts)[1] = grp
merge(counts, result, sort = FALSE)
}
Creating a string in R with in it
In the string, there is already a double quote. So, we can wrap it with single quotes
Input <- '?jql=filter%20=%20"Plan%20Standup%20-%20Mutual-SA'
cat(Input, "\n")
#?jql=filter%20=%20"Plan%20Standup%20-%20Mutual-SA
Related Topics
Use Dplyr to Concatenate a Column
How to Deploy Shiny App That Uses Local Data
Find Matches of a Vector of Strings in Another Vector of Strings
Additional Metrics in Caret - Ppv, Sensitivity, Specificity
Replace Na with Previous and Next Rows Mean in R
Rbuildignore and Excluding Directories
How to Use Tidyr to Fill in Completed Rows Within Each Value of a Grouping Variable
Robust and Clustered Standard Error in R for Probit and Logit Regression
Draw Lines Between Different Elements in a Stacked Bar Plot
Adding Multiple Columns in a Dplyr Mutate Call
Print Tibble with Column Breaks as in V1.3.0
Plot Dates on the X Axis and Time on the Y Axis with Ggplot2
How to Remove Leading "0." in a Numeric R Variable