An issue with tiff and ggplot R functions inside for loop - r

]
2
I was not able to get a batch of images with tiff() R function inside for loop.
I have x86_64-w64-mingw32/x64 (64-bit) platform with installed Windows 8.1 and RStudio Version 1.0.143 with R version 3.6.0 (2019-04-26) -- "Planting of a Tree". I tried to obtaine a batch of tiff images by putting my code inside the for loop. Unfortunately that resulted in the numerous broken files (in attachment). But if i type exactly the same code in the RStudio console i got normal (valid) image.
#Fragment of the script
for (i in 1:nrow(BH))
{
...
tiff( paste(pos$rs[1],"tiff",sep = '.'))
ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill='')
dev.off()
}
#If i perform the following code in console after script execution i got a valid image
tiff( paste(pos$rs[1],"tiff",sep = '.'))
ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill='')
dev.off()

The solution was to envelop ggplotfunction by base print function in the loop:
print(ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill=''))
So, i've used the solution from the other post:
enter link description here

Related

Rmarkdown fails to render inline plots when opened within an R project on GoogleDrive

I have an R project held onto a Google Drive. I access both the R project and associated markdowns using the Google Drive desktop app. I recently updated my macOS to Monterey 12.2.1 and since then, I haven't been able to render plots inline within a markdown. I get the following error message when trying to print any plot:
Error in dev.off() :
QuartzBitmap_Output - unable to open file '/Volumes/GoogleDrive/Shared drives/.../.Rproj.user/shared/notebooks/-.../1/s/cqgw7b5dagxzw_t/_rs_chunk_plot_001.png'
This seems to be specific when opening a markdown, within an R project, onto a Google Drive. I have tried having a project on my local machine and opening the same markdown, plots display inline fine. I have tried opening the markdown outside of a project, again, can display plots inline fine. The plots also display in the viewer pane fine regardless and knitting is also not an issue.
The only clue I have is that when I go within the .Rproj.user directory, I can find a folder with the naming 'cqgw7b5dagxzw' (see path above), but it is missing the '_t'. Not sure what that could mean though.
Since updating the OS I have also reinstalled XQuartz.
I can still get to the plots, so it's not a HUGE issue, but the inline display feature is rather handy to make quick modifications to my visualisations.
Below are some session info.
Thanks!!!
PS: Plot twist! I can display plots inline with ggplotly?!?!
Workaround
I found this workaround which displays the plots in the viewer pane instead. It is definitely an improvement, but displaying plots inline allows you to get an idea of the proportions of the plot you will eventually knit.
> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.2.1
Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
I found an issue someone logged on Rstudio github relates to this, linked here.
It seems you're right about the niche scenario of Rmarkdown + R Project + Google Drive + Inline plotting.
Someone in the comments suggested going to Preferences>General>Graphics and changing the back end option to Cairo instead of Quartz. Tried that on my end and seems to work when I tried a basic histogram with GGplot2.
Not sure if using Cairo makes anything else worse though.
Using MacOS Monteray (12.3.1) if that helps.

Unable to save/open pdf file in R

I am new to R programming and I am trying to learn it. So, please bear with me if this question is silly!
I am trying to execute the below code in RStudio and I get the following error:
R version 3.6.2 (2019-12-12) -- "Dark and Stormy Night"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)
[Workspace loaded from ~/.RData]
> x=rnorm(100)
> y=rnorm(100)
> pdf("Figure.pdf")
**Error in pdf("Figure.pdf") : cannot open file 'Figure.pdf'**
> plot(x,y, col="green")
> dev.off()
null device
I am unable to save or open the pdf file. I tried t o check my permissions and I also ran the Rstudio with administer rights but no luck!
One can direct the output of R graphics functions to PDF files through the use of the pdf() function.
The file = argument is a named argument (versus a positional argument), and therefore one needs to use the name in order to change its value. The reasoning for this is that the PDF device function's default value for file = allows multiple PDFs to be written, per the R documentation for pdf().
x=rnorm(100)
y=rnorm(100)
pdf(file = "Figure.pdf")
plot(x,y, col="green")
dev.off()
...produces a PDF in the current R working directory that contains the following image.

Cannot create PDF by ggplot2 within if-statements

Consider a minimal example: generating an empty plot with ggplot2 and put it into a PDF file. Typically people would do
pdf()
ggplot()
dev.off()
and it works as expected. However, when you wrap these statements into an if-statement, the resulting PDF file becomes corrupted.
if (TRUE) {
pdf()
ggplot()
dev.off()
}
This issue has been reproduced on both Windows 10 and macOS Mojave. I'm using the latest version of R
$ R --version
R version 3.6.0 (2019-04-26) -- "Planting of a Tree"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin18.6.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/.
To save a ggplot object using pdf or jpg functions, one has to explicitly print the ggplot.
if (TRUE) {
pdf()
print(ggplot())
dev.off()
}
This is stated in R-FAQ 7.22 Why do lattice/trellis graphics not work?
The most likely reason is that you forgot to tell R to display the graph. Lattice functions
such as xyplot() create a graph object, but do not display it (the
same is true of ggplot2 graphics, and Trellis graphics in S-PLUS). The
print() method for the graph object produces the actual display. When
you use these functions interactively at the command line, the result
is automatically printed, but in source() or inside your own functions
you will need an explicit print() statement.
So, it would not save if one simply source a script even in the absence of a conditional statement or loop (source with echo = TRUE would save the plot).
I personally prefer to use the ggsave function since it seems more flexible.
if (TRUE) {
ggplot()
ggave(filename = "plot.pdf")
}

How to embed/display code in texmaker?

I am new to texmaker. I have difficulty in displaying the codes and results I got from R in my texmaker document.
For example I have this results:
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-w64-mingw32/x64 (64-bit)
How do I display that in texmaker that it looks like the one you are seeing? (indented, gray background, looks like a code from R).
What do I need to have?
Thanks!
Would the listings package (which supports R) achieve what you want?: http://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings
In LaTeX you can also just use the verb(atim) environment for fixed-width, not interpreted text:
/begin{verb}
> R code goes here...
/end{verb}
?
If you want to display both the command and the results, then don't you need to execute the R code? (Unless you are planning to copy and paste the results...).
I would suggest checking out the knitr package.

R function called when pressing Ctrl+D

What function (if any) is called when pressing Ctrl+D to exit R repl? I saw in a few questions, such as:
How to disable "Save workspace image?" prompt in R?
Expert R users, what's in your .Rprofile?
code that led me to believe it's calling either function q or quit.
The reason I want to override is to make the pesky:
Save workspace image? [y/n/c]:
prompt on exit go away. However, overriding the function in .Rprofile such as:
quit <- function(...) {
print(1)
}
and similarly for q did not work - i.e. pressing Ctrl-D did not actually print number 1, went straight to the prompt.
The solutions presented in the above links did not seem to work. R version used:
R version 2.15.2 (2012-10-26) -- "Trick or Treat"
Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-pc-linux-gnu (64-bit)
Ctrl-D does not call any function, it is special keyboard interrupt.
Try pressing Ctrl-D, then answer c for cancel. If you press the up arrow to get the last command, you'll see it's not there.
To override the pesky Save workspace image? [y/n/c]:, see the answer to this question:
To summarise you have three options:
Calling R --no-save instead of R,
Loading the following in the interactive R session (won't work from .Rprofile):
require(Defaults)
setDefaults(q, save="no")
useDefaults(q)
Or put the following in your .Rprofile:
# Set hook to be run when Defaults is attached
setHook(packageEvent("Defaults", "attach"),
function(...) { setDefaults(q, save="no"); useDefaults(q) })
# add Defaults to the default packages loaded on startup
old <- getOption("defaultPackages");
options(defaultPackages = c(old, "Defaults"))
EDIT:
Here's another hack I can think of since the above haven't worked for your case. It's not an R solution, but might do the trick?
First, move you R executable file (for the purposes of this example i'm going to assume it's in /usr/bin/) to a new file, something like:
sudo mv /usr/bin/R /usr/bin/Rold
Now set up a new bash script as /usr/bin/R:
#!/bin/bash
/usr/bin/Rold --no-save "$#"
and chmod it to have the right permissions.

Resources