Suppressing error message from heatmap.2 in knitr/Rmarkdown - r

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.

Related

Unexplained R failure: Error: attempt to use zero-length variable name

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.

grDevices::dev.new() does not work in the first time

My question: How to let grDevices::dev.new() work well ?
To avoid the error Error in plot.new() : figure margins too large coursing the small plot region,
I wrote the code grDevices::dev.new() in the front of plot().
However this code does not work in the first time (or after pushing the button .clean all plot button )
And this cause the errors (e.g., in the R CMD check).
Do I misunderstand the function grDevices::dev.new() ?
REF?:
R: Open new graphic device with dev.new() does not work
Answer
Using grDevices::windows() instead of grDevices::dev.new(), I overcome the issues.
Unfortunately, we cannot use grDevices::windows() , because the following error occurs in the R CMD check:
Error in grDevices::windows() :
screen devices should not be used in examples etc

How can knitr know whether the R code evaluation has error?

The knitr would always evaluate the R code before formatting the output, so just wondering how can I know whether the R code evaluation has error. Thanks
Basically it boils down to three lines of code in the evaluate package. The key is withCallingHandlers(), which can be used to capture errors, messages, and warnings, etc. A minimal example:
withCallingHandlers(1 + 'a', error = function(e) {
cat('An error occurred! The error object is:\n')
str(e)
})
If you don't want the error to halt R, you can wrap the code in try().

Knitting returns parse error

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.

Suppress all output from the compute.es functions

I'm using the compute.es package (http://cran.r-project.org/web/packages/compute.es/compute.es.pdf) to compute effect sizes. Now, when using one of the functions from this package, the result is printed even though you assign it to a vector, and I would like to surpress this.
For example,
library("compute.es")
mes(5,5,5,5,5,5,level=95,dig=2,id=NULL,data=NULL)
prints a lot of information. By using capture.output like so
library("compute.es")
capture.output(mes(5,5,5,5,5,5,level=95,dig=2,id=NULL,data=NULL))
a lot of it gets suppressed, but not all. I've had no luck with sink() (which breaks the whole function) or invisible() either.
How can I suppress all printed information from this function?
Version 0.2-4 of the compute.es package has a 'verbose' argument, so e.g.:
require(compute.es) # VERSION => 0.2-4
des(.3, 30, 30, verbose=FALSE) # WILL SUPPRESS PRINTING TO CONSOLE
This function is really bi-polar. Some things are printed using cat, others using message. In addition to what you've tried you can also try suppressMessages.
This worked for me.
x <- capture.output(suppressMessages(mes(5,5,5,5,5,5,level=95,dig=2,id=NULL,data=NULL)))
Alternatively, you can hack the function (use the source!) and cut out all the cat and message statements. Another way would be to add another argument to the function (like verbose) and turn on/off messages by putting them inside an if clause. E.g.
if (!is.null(data)) {
if (verbose) {
cat("\n")
message(" EFFECT SIZE CALCULATION (FOR VECTOR INPUT)")
cat("\n")
}
...

Resources