I am trying to specify the size of a plot dynamically in RMarkdown. Because it is a facetted plot with a dynamic number of plots, the aspect ratio needs to change.
I'm using this code:
...
jobs_levels <- 9
```
#### Figure 3.1.1. Effect of Inidivdual Interventions in Living Rooms
```{r figure_3_3_1, fig.height=jobs_levels}
jobs_levels
print(figure_3_3_1)
```
For the sake of simplicity, I've hard coded the jobs_levels (the number of levels in the facetting factor). As you can see, I set the value very clearly,and then use it in the very next code chuck. I can see the value clear as day in the environment. It is 9. But I get this:
Error in eval(ele) : object 'jobs_levels' not found
> ```{r figure_3_3_1, fig.height=jobs_levels}
Error: attempt to use zero-length variable name
When I run this in batch mode, it crashes. Any idea what is going on with this?
I even put in the extra lines:
jobs_levels
to debug. EAch time I run one of those lines with cotrl enter, it evaluates right, but I see the error message again too...
The error message makes it look as though you are trying to evaluate the chunk header as R code. You had
```{r figure_3_3_1, fig.height=jobs_levels}
The first two backticks would be parsed as a zero length variable name, as the error message states.
You can't run R Markdown code as R code, you need to use rmarkdown::render or a related function to run it.
Related
I got the error message:
Error: object 'x' not found
Or a more complex version like
Error in mean(x) :
error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
What does this mean?
The error means that R could not find the variable mentioned in the error message.
The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x already, use a different variable name.)
x
## Error: object 'x' not found
The more complex version of the error has the same cause: calling a function when x does not exist.
mean(x)
## Error in mean(x) :
## error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
Once the variable has been defined, the error will not occur.
x <- 1:5
x
## [1] 1 2 3 4 5
mean(x)
## [1] 3
You can check to see if a variable exists using ls or exists.
ls() # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.
Errors like this can occur when you are using non-standard evaluation. For example, when using subset, the error will occur if a column name is not present in the data frame to subset.
d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found
The error can also occur if you use custom evaluation.
get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found
In the second case, the var function cannot be found when R looks in the utils package's environment because utils is further down the search list than stats.
In more advanced use cases, you may wish to read:
The Scope section of the CRAN manual Intro to R and demo(scoping)
The Non-standard evaluation chapter of Advanced R
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run".
This error usually comes up when we don't select our statements and click on "Run".
Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:
check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.
Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.
Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:
{r sourceDataProb1, echo=F, eval=F}
# some code here
The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.
Lastly: did you remove the variable or clear it from memory after declaring it?
rm() removes the variable
hitting the broom icon in the evironment window of RStudio clearls everything in the current working environment
ls() can help you see what is active right now to look for a missing declaration.
exists("x") - as mentioned by another poster, can help you test a specific value in an environment with a very lengthy list of active variables
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
I'm going to add this on here even though it's not a new question as it comes quite highly in the search results for the error:
As mentioned above, re checking syntax, if you're using dplyr, make sure you have all the %>% pipes at the end of the lines above the error, otherwise the contents of anything like a select statement won't pass down into the next part of the code block.
When running all the chunks in the markdown file it works perfectly but when I knit it shows an error for the select function.
I have called library(dplyr) so I don't see why there should be an error.
If I remove the select function and use $len in the later code there is no problem. I don't understand why the select function is giving an error.
Also, the Toothgrowth data has not been modified before this thus there are 60 observations of 3 variables len,supp and dose.
D.5<-ToothGrowth%>%filter(dose==0.5)%>%select(len)
D1<-ToothGrowth%>%filter(dose==1)%>%select(len)
D2<-ToothGrowth%>%filter(dose==2)%>%select(len)
error in select(.,len) unused argument (len)
this is the error message
In attempting to knit a PDF. I'm calling a script that should return two ggplots by calling the chunk:
```{r, echo=FALSE}
read_chunk('Script.R')
```r
But receive the error
processing file: Preview-24a46368403c.Rmd
Quitting from lines 9-12 (Preview-24a46368403c.Rmd) Error in
parse(text = x, srcfile = src) : attempt to use zero-length
variable name Calls: <Anonymous> ... <Anonymous> -> parse_all ->
parse_all.character -> parse Execution halted
The script on its own runs and returns the two plots, but won't return them when knitted.
Similarly attempted to use source()
But got a similar error
Quitting from lines 7-10 (Preview-24a459ca4c1.Rmd) Error in
file(filename, "r", encoding = encoding) : cannot open the
connection Calls: <Anonymous> ... withCallingHandlers -> withVisible
-> eval -> eval -> source -> file Execution halted
While this does not appear to be a solution for you, this exact same error message appears if the chunk is not ended properly.
I experienced this error and traced it to ending chunk with `` instead of ```. Correcting the syntax of the chunk solved the problem I experienced with the same error message as you.
Are you sure that knitr is running from the directory you think it is? It appears that it is failing to find the file.
use an absolute path, if that fixes it, you've found your problem
once you've done that, you can use opts_knit$set(root.dir = "...") -- don't use setwd(.) if you want it (the cwd) to be maintained.
Knitr's default is the directory of the .Rmd file itself.
It may have to do with the "r" at the end of the triple backquotes demarcating your code chunk. There should be nothing after the triple backquotes, but I think the problem is specifically that the letter is "r".
The issue stems from the fact that R markdown processes backquoted statements starting with r as inline code, meaning it actually runs whatever is between the backquotes.
I had similar issues writing a problem set in an Rmd with this statement, which had backquoted text intended to be monospace but not run as inline code:
Use sapply or map to calculate the probability of a failure rate over r <- seq(.05, .5, .025).
When I knit the document, I got opaque error messages saying I had an improper assignment using <-. It was because instead of just displaying the backquoted statement in monospace, r <- seq(.05, .5, .025) was actually processed as R inline code of <- seq(.05, .5, .025)...thus the improper assignment error. I fixed my error by changing the variable name from r to rate.
The actual text of the error message in your question might refer to whatever follows your code chunk, as the knitting process is probably trying to run that as code. In this case, just removing that stray r at the end of the code chunk should fix the error.
You should use the following similar syntax, I had the same exact issue but got it fixed:
```{r views}
bank.df <- read.csv("C:/Users/User/Desktop/Banks.csv", header = TRUE) #load data
dim(bank.df) # to find dimension of data frame
head(bank.df) # show first six rows
```
the ``` has to be in the end of the line.
In my case was that I finished the code with four comas, not three . Check this and If you finished with four comas too, try to delete one of them.
I am trying to generate a plot using heatmap.2 and print to a pdf_document using Rmarkdown.
Whether I call heatmap.2 from the console or in an .Rmd, the plot appears perfectly exactly as I want it. But additionally, I receive the error message:
## Error in plot.new(): figure margins too large
I can force knitr to continue processing using error=TRUE, but the error message is still printed. I also have set
echo=FALSE, warning=FALSE, message=FALSE
which I thought would suppress the message, but it doesn't. I have tried using invisible() as per this question, but it seems to do nothing.
I have also tried "fixing" the error by adjusting my plot parameters in heatmap.2 with no success-- it seems to complain when one of my columns in lhei is too skinny. Since the plot looks fine, I am not worried about it unless there is no other way to suppress this error message.
How can I suppress this error message in my Rmarkdown pdf?
A pretty robust way of suppressing error messages is to wrap an expression in try(...,silent=TRUE). As a general example, if we use the following code to set up a plot layout
plotIDs <- matrix(c(1:16), 4, 4, byrow = T)
layout(plotIDs, widths = c(0.5,1,1,1,1), heights = c(0.5,1,1,1,1))
calling frame() afterwards will produce an error:
R> frame()
Error in frame() : figure margins too large
Wrapping this with try, i.e.
R> try(frame(),silent=TRUE)
R>
will not produce an error message in the console.
Is there a way to disable the storing of tracebacks on error in R temporarily (for a session)?
The reason I ask is that ggplot2 has a long-running problem, that they've been unable to fix. Somehow the entire dataset gets stored in the traceback, and if you work with very large datasets, this means that a mis-typed variable name can leave you with a 10-minute hang.
Especially when I make complex plots for very large data, this is crippling. Usually these are all small typos, I don't ever need tracebacks, just the error message would be fine.
I tried
options(error = expression(NULL))
but apparently that handler is called after the traceback is stored (the hang persists).
reproducible example
library(ggplot2)
data(diamonds)
diamonds = diamonds[sample(x=nrow(diamonds),size=200000,replace=T),]
qplot(data=diamonds, wrong, var)
One obvious thing that I hadn't thought about is to wrap the call in tryCatch, like this:
tryCatch({
print(qplot(data=diamonds, wrong, var))
}, error = function(e){warning(e)})
It's important to print your plot inside the tryCatch, as otherwise the error occurs once the returned plot object is automatically printed.
I would still be interested in the reverse equivalent of options(warn=2) (i.e. instead of turning warnings into errors so that they can be traced, it would turn errors into warnings, so they don't generate a huge traceback).