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

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

Related

Why am I receiving "plow.new has not been called yet" when trying to plot PCAs?

This is the end goal however when trying to plot the code below
plot(PCAloadings[,1:2], arrows(0,0,PCAloadings[,1],PCAloadings[,2]), text(PCAloadings[,1:2], labels=rownames(PCAloadings))
I recieve the following error:
in text.default(PCAloadings[, 1:2], labels = rownames(PCAloadings)) : plot.new has not been called yet
I am unsure how to resolve this issue or what it pertains to, any help is welcome.
EDIT: when trying to run line by line only the first line runs. When trying to run arrows or text lines I run into the same error
plot(PCAloadings[,1], PCAloadings[,2])
This is the output from the first line alone
Seems to be a syntax problem. Try
plot(PCAloadings[,1:2])
arrows(0,0,PCAloadings[,1],PCAloadings[,2])
text(PCAloadings[,1:2], labels=rownames(PCAloadings))

Error in file(con, "w") : cannot open the connection [Using R-Studio to plot interactive bar graphs using rCharts, knitr]

I am getting an error when I am trying to run the code below in R-Studio 3.3.2 on a Mac (OS Sierra)
devtools::install_github('ramnathv/rCharts')
install.packages("knitr")
require(rCharts)
require(knitr)
haireye <- as.data.frame(HairEyeColor)
n1 <- nPlot(Freq ~ Hair, group = 'Eye', type = 'multiBarChart',
data = subset(haireye, Sex == 'Male')
)
n1$save('fig/n1.html', cdn = TRUE)
cat('<iframe src="fig/n1.html" width= 100%, height=600</iframe>')
Pls see output below:
Error in file(con, "w") : cannot open the connection
In addition: Warning message: In file(con, "w") : cannot open file 'fig/n1.html': No such file or directory
But I am able to generate the reqd bar graph in the viewer when I use:
n1$show(cdn = TRUE)
in lieu of n1$save('fig/n1.html', cdn = TRUE)
To take care of write permission issues (if any), I also tried including the line below, altering the WD path wherever necessary.
knitr::knit2html('Users/documents/n1.html')
But it did not help. I see the n1.html file created but it only opens an empty browser.
Any help to resolve this is appreciated.
Best,
S
A lot of times we face this error due to caching in RStudio and in that case, actual code errors don't show up. Restart RStudio and this error will be gone and actual code errors would show.
You have two separate problems.
The connection error appears because the fig/ folder does not exist. Create the folder and the save command will work. R has functions to check the existance of directories and create new ones if you would like to do it in your code.
The second problem comes from the way you save, you should use n1$save('fig/n1.html', standalone = TRUE). Here you have a similar situation.
As a side-note, I would say rCharts is not currently developed or mantained at all, so I would recommend you to use another library for your charts. In my opinion Plotly is quite nice. rCharts brought the NVD3 project to R and the chart style is in my opinion really nice. However, as far as I know both projects are stopped so I would look for a library that is still alive.
I have fixed this problem with good old rm(list=ls()) . I know I have
fallen into sequences where the error stops execution of my script. I fix the error, and then it won't run. This is likely due to lazy evaluation but it is a near impossible problem to diagnose, so the solution at the top works almost all the time.

How do I close unused connections after read_html in R

I am quite new to R and am trying to access some information on the internet, but am having problems with connections that don't seem to be closing. I would really appreciate it if someone here could give me some advice...
Originally I wanted to use the WebChem package, which theoretically delivers everything I want, but when some of the output data is missing from the webpage, WebChem doesn't return any data from that page. To get around this, I have taken most of the code from the package but altered it slightly to fit my needs. This worked fine, for about the first 150 usages, but now, although I have changed nothing, when I use the command read_html, I get the warning message " closing unused connection 4 (http:....." Although this is only a warning message, read_html doesn't return anything after this warning is generated.
I have written a simplified code, given below. This has the same problem
Closing R completely (or even rebooting my PC) doesn't seem to make a difference - the warning message now appears the second time I use the code. I can run the querys one at a time, outside of the loop with no problems, but as soon as I try to use the loop, the error occurs again on the 2nd iteration.
I have tried to vectorise the code, and again it returned the same error message.
I tried showConnections(all=TRUE), but only got connections 0-2 for stdin, stdout, stderr.
I have tried searching for ways to close the html connection, but I can't define the url as a con, and close(qurl) and close(ttt) also don't work. (Return errors of no applicable method for 'close' applied to an object of class "character and no applicable method for 'close' applied to an object of class "c('xml_document', 'xml_node')", repectively)
Does anybody know a way to close these connections so that they don't break my routine? Any suggestions would be very welcome. Thanks!
PS: I am using R version 3.3.0 with RStudio Version 0.99.902.
CasNrs <- c("630-08-0","463-49-0","194-59-2","86-74-8","148-79-8")
tit = character()
for (i in 1:length(CasNrs)){
CurrCasNr <- as.character(CasNrs[i])
baseurl <- 'http://chem.sis.nlm.nih.gov/chemidplus/rn/'
qurl <- paste0(baseurl, CurrCasNr, '?DT_START_ROW=0&DT_ROWS_PER_PAGE=50')
ttt <- try(read_html(qurl), silent = TRUE)
tit[i] <- xml_text(xml_find_all(ttt, "//head/title"))
}
After researching the topic I came up with the following solution:
url <- "https://website_example.com"
url = url(url, "rb")
html <- read_html(url)
close(url)
# + Whatever you wanna do with the html since it's already saved!
I haven't found a good answer for this problem. The best work-around that I came up with is to include the function below, with Secs = 3 or 4. I still don't know why the problem occurs or how to stop it without building in a large delay.
CatchupPause <- function(Secs){
Sys.sleep(Secs) #pause to let connection work
closeAllConnections()
gc()
}
I found this post as I was running into the same problems when I tried to scrape multiple datasets in the same script. The script would get progressively slower and I feel it was due to the connections. Here is a simple loop that closes out all of the connections.
for (i in seq_along(df$URLs)){function(i)
closeAllConnections(i)
}

ggsave error: cannot find function "dev"

I get the following error when trying to save my ggplot:
Error in ggsave(paste0(projDir, "figs/lmGtaGridCombined.png")) :
could not find function "dev"
This was code that worked earlier this year, before the newest ggplot(2.0.0). The 3rd party code I'm using (https://rpubs.com/Koundy/71792; which uses ggthemes) worked great earlier this year to make my images more publication-friendly. However, now the ggthemes code gave errors related to:
Error in FUN(X[[i]], ...) :
Theme element 'text' has NULL property: margin, debug
In addition: Warning message:
`axis.ticks.margin` is deprecated. Please set `margin` property of `axis.text` instead
>
which I thought I fixed by changing this line:
text = element_text()
to this:
text = element_text(margin=margin(), debug= F),
which made a version of my image print, but many aspects (ie, x-label spacing flush instead of offset) not right. Plus- ggsave gave the above error, which is now my biggest problem, as I am considering manually fixing the image if I can just get it to print similarly to as it did before.
I've tried png ..... dev.off but I can't get it to print in the right dimensions and resolution as it did originally with ggsave.
Please help. I've been scared to post on stackoverflow up until now, but I'm very desperate. Thanks in advance.

Problems with reassignInPackage

I am trying to understand the way the YourCast R package works and make it work with my data.
For example, if a function produces errors, I
get the source code of that function using YourCast:::bad.fn
add outputs of critical
values at critical stages
use reassignInPackage(name="original.fn", package="YourCast", value="my.fn")
Once I find the cause of the error, I fix it in the function and reassign it in the package.
However, for some strange reason this does not work for non-hidden functions.
For example:
install.packages("YourCast")
Library(YourCast)
YourCast:::check.depvar
This will print the hidden function check.depvar. One line if (all(ix == 1:3)) will produce an error message if any of the x is missing.
Thus, I change the whole function to the following and replace the original formula:
mzuba.check.depvar <- function(formula)
{
return (grepl("log[(]",as.character(formula)[2]))
}
reassignInPackage("check.depvar",
pkgName="YourCast",
mzuba.check.depvar)
rm(mzuba.check.depvar)
Now YourCast:::check.depvar will print my version of that function, and everything is fine.
However
YourCast::yourcast or YourCast:::yourcast or simply yourcast will print the non-hidden function yourcast. Suppose I want to change that function as well.
reassignInPackage(name="yourcast",
pkgName="YourCast",
value=test)
Now, YourCast::yourcast and YourCast:::yourcast will print the new, modified version but yourcast still gives the old version!
That might not a problem if I could simply call YourCast::yourcast instead of yourcast, but that produces some kind of error that I can't trace back because suddenly R-Studio does not print error messages at all anymore!, although it still does something if it is capable to:
> Uagh! do something!
> 1 + 1
[1] 2
> Why no error msg?
>
Restarting the R-session will solve the error-msg problem, though.
So my question is: How do I reassign non-hidden functions in packages?
Furthermore (this would faciliate testing a lot), is there a way to make all hidden functions available without using the ::: operator? I.e., How to export all functions from a package?

Resources