Error knitting from R Markdown ggplot - unexpected special character that doesn't exist

159 views Asked by At

I'm getting an error when I try to knit my .Rmd file. The code itself runs fine inside the file; the error only occurs when I try to knit.

Quitting from lines 103-118 [unnamed-chunk-4] (Lab-14.Rmd)
Warning messages:
1: In eng_r(options) :
  Failed to tidy R code in chunk 'unnamed-chunk-2'. Reason:
Error in base::parse(text = code, keep.source = keep.source) : 
  <text>:4:21: unexpected SPECIAL
3: geography = 'tract' ,
4: county = counties , %
                       ^

2: In eng_r(options) :
  Failed to tidy R code in chunk 'unnamed-chunk-3'. Reason:
Error in base::parse(text = code, keep.source = keep.source) : 
  <text>:5:63: unexpected SPECIAL
4: theme_minimal ( ) +
5: scale_fill_viridis_c ( option = "magma" , direction = - 1 ) + %
                                                                 ^

Execution halted

In essence, it appears it's somehow encountering a special character that's causing it to quit, but the special character it says it is encountering doesn't exist. Namely, there is no errant % sign despite what knitr may think. Here are the lines in question.

{r tidy=TRUE, tidy.opts=list(width.cutoff=68)}
all_2014 <- ggplot(bunc.SNAP_geq_Pov, aes(fill = percent_geq_pov)) + 
  geom_sf(color = "black", size = .5) +  
  theme_minimal() +
  scale_fill_viridis_c(option = "magma", direction = -1) + ggtitle("2014") +
  theme(plot.title = element_text(size = 8, face = "bold")) +
  # facet_wrap(~county) + 
  # Here, it will place them together to form the overall area but I can't delineate between county boundaries since this is on the tract level
  theme(
    panel.grid.major.x = element_blank(),  
    panel.grid.minor.x = element_blank(), 
    panel.grid.major.y = element_line(),   
    panel.grid.minor.y = element_blank(),  
    axis.text = element_text(angle = 30, vjust = 1, hjust = 0.8, size = 5),
    legend.position = "none" 
  )

And here are the libraries I am using.

library(tidyverse)
library(dplyr)
library(pander)
library(ggplot2)
library(GGally)
library(sf)
library(mapview)
library(tigris)
library(tidycensus)
library(tmaptools)
library(patchwork)
library(viridis)
options(tigris_use_cache = TRUE) # trying to silence those warnings

As I said, everything runs fine with 0 errors inside the .Rmd file; I am only encountering this problem with knitting.

1

There are 1 answers

0
Yihui Xie On

If you use tidy = TRUE, you cannot write comments after an incomplete expression (see documentation here). You have to either remove the chunk option tidy = TRUE, or move the comments before or after a complete expression.