Expression() command just prints itself - r

apologies for the trivial nature of this question. I have searched for other instances of this and can't find any.
I am trying to combine the expression() function with paste(), for example to do: expression(paste("TNF", alpha))
But everytime I enter a command using expression() I just get my command returned to me, so the above command just prints:
expression(paste("TNF", alpha))
What am I doing wrong?

Ah ok I had misinterpreted the function ofexpression() and it seems it's interpreted the way I wanted it to be within the scale_x_discreet() call when building my plot in ggplot2.
In case it's useful to anyone else, my code became (where a is a ggplot object):
a + scale_x_discrete(labels=c("Vehicle", expression(paste("TNF", alpha))))
Which then produced a group label of "TNFα".

Related

Beginner: R custom plot function doesn't run all lines?? (Quantmod)

Basic question on trying to use a function to plot (using Quantmod).
Function runs the 'chartSeries function' seems to skip the next lines and runs the addBBands command (or whichever 'add'-command is last.
Have tried to use Sys.sleep() in there thinking it was due to r not having enough time to pull the graphic, but to no avail.
Any ideas welcome!
Code:
QuantPlot2019<-function(stockname){
chartSeries(Stockname,subset='2019-01-01::2019-12-31',theme=chartTheme('white'))
addEMA(n=30,col='magenta')
addMACD(fast=12,slow=26,signal=9,type='EMA')
addBBands(n=20,sd=2)
}
getSymbols("...")
Stockname<-...
QuantPlot2019()
Thanks
Try the function below and see if it works:
QuantPlot2019<-function(stockname){
chartSeries(eval(parse(text=Stockname)),subset='2019-01-01::2019-12-
31',theme=chartTheme('white'))
addEMA(n=30,col='magenta')
addMACD(fast=12,slow=26,signal=9,type='EMA')
addBBands(n=20,sd=2)
}

utils::globalVariables(.) not applicable to R CMD CHECK note:no visible binding for global variable '.' [duplicate]

I noticed in checking a package that I obtain notes "no visible binding for global variable" when I use functions like subset that use verbatim names of list elements as arguments.
For example with a data frame:
foo <- data.frame(a=c(TRUE,FALSE,TRUE),b=1:3)
I can do silly things like:
subset(foo,a)
transform(foo,a=b)
Which work as expected. The R code check in R CMD however doesn't understand that these refer to elements and complains about there not being any visible bindings of global variables.
While this works ok, I don't really like having notes in my package and prefer for it to pass the check with no errors, warnings and notes at all. I also don't really want to rework my code too much. Is there a way to write these codes so that it is clear the arguments do not refer to global variables?
To get it past R CMD check you can either :
Use get("b") (but that is onerous)
Place a=b=NULL somewhere higher up in your function (that's what I do)
There was a thread on r-devel a while ago where somebody from r-core basically said (from memory) "NOTES are ok, you know. The assumption is that the author checked it and is ok with the NOTE.". But, I agree with you. I do prefer to have CRAN checks return a clean "OK" on all platforms. That way the user is left in no doubt that it passes checks ok.
EDIT :
Here is the r-devel thread I was remembering (from April 2010). So that appears to suggest that there are some situations where there is no known way to avoid the NOTE, but that's ok.
This is one of the potential "unanticipated consequences" of using subset non-interactively. As it says in the Warning section of ?subset:
This is a convenience function intended for use interactively. For
programming it is better to use the standard subsetting functions like
‘[’, and in particular the non-standard evaluation of argument
‘subset’ can have unanticipated consequences.
From R version 2.15.1 onwards there is a way around this:
if(getRversion() >= "2.15.1") utils::globalVariables(c("a", "othervar"))
As per the warning section of ?subset it is better to use subset interactively, and [ for programming.
I would replace a command like
subset(foo,a)
with
foo[foo$a]
or if foo is a dataframe:
foo[foo$a, ]
you might also like to use with if foo is a dataframe and the expression to be evaluated is complex:
with(foo, foo[a, ])
I had this issue and traced it to my ggplot2 section.
This code provided the error:
ggplot2::ggplot(data = spec.df, ggplot2::aes(E.avg, fraction)) +
ggplot2::geom_line() +
ggplot2::ggtitle(paste0(title))
Adding the data name to the parameters eliminated the not:
ggplot2::ggplot(data = spec.df, ggplot2::aes(spec.df$E.avg, spec.df$fraction)) +
ggplot2::geom_line() +
ggplot2::ggtitle(paste0(title))

In R, how do I save a data.tree plot to a file?

I'm unable to save a plot generated by the plot.Node function in data.tree. I've tried the following:
### Create tree object and plot it
data(acme);
plot(acme);
This works fine, showing the plot, as one would expect.
### Try saving it as png
png(filename='file.png', type='cairo-png');
plot(acme);
dev.off();
This creates an empty file. ggsave does the same. Apparantly, plot.Node uses DiagrammeR under the hood, so I looked into that package. It has a function to export graphs:
export_graph(acme, file_name="file.png");
This gives the error:
Error in file.exists(diagram) : invalid 'file' argument
When I transform to GraphViz first, I get a different error:
export_graph(ToGraphViz(acme), file_name="file.png");
Error in graph$dot_code : $ operator is invalid for atomic vectors
Clearly, exporting to GraphViz doesn't quite export to what DiagrammeR expects.
I'm in RStudio and so could in theory just save the plot using the GUI, but I need this for in a script.
Apparently, plot.Node doesn't actually plot anything - instead it seems to generate html/js. Does this mean that that result cannot be stored as a graphic? Or is there some export/conversion function somewhere that I'm completely missing? it certainly feels like I'm missing something obvious - I assume the need to store plotted data.trees as images is quite common. But I have no idea which potential solutions I can still explore.
I'd be very grateful for any pointers anybody has!
As sebastian-c suggested, things work now a bit differently than suggested by Matherion, as of R 3.3.3 with data.tree 0.7.0 and DiagrammeR 0.9.0
Pre-requisite: DiagrmmeRsvg and dependencies need to be installed. Depending on your OS, for this to work you might have to install V8. For example on ubuntu:
apt-get install libv8-3.14-delibv8-3.14-dev
And then in R:
install.packages("DiagrammeRsvg")
On Windows, I didn't have to install anything (maybe because Chrome is installed?).
Once DiagrammeRsvg is available, run:
library(data.tree)
data(acme)
library(DiagrammeR)
export_graph(ToDiagrammeRGraph(acme), "export.pdf")
I've found the answer, at least, partially. There exists a package dedicated to exporting GraphViz diagrams to SVG: DiagrammeRsvg.
So this works:
treeAsSVG <- export_svg(grViz(ToGraphViz(acme)));
writeLines(treeAsSVG, "filename.svg"));
The grViz is necessary to actually convert the ToGRaphViz output to something that can be interpreted by export_svg. I'm still not really sure (yet) what all goes on under the hood - for example, this does not work:
export_graph(grViz(ToGraphViz(acme)), file_name="filename.svg");
But, if anybody else has a similar problem and stumbles upon this question, perhaps this partial answer can help them to at least export something that can then be integrated in e.g. html pages.
By converting acme with as.phylo() it works, but it looks a little boring:
plot(as.phylo(acme),
show.node.label=TRUE,
node.pos=2,
no.margin=TRUE
)
# adding edge labels
edgelabels(as.vector(acme$Get("cost"))[-1],
adj = c(0,-0.5),
frame = "none")
solution with as.phylo()
I also tried as.igraph. However, the nodes overlap and it looks even less pretty:
plot(0, type="n", ann=FALSE, axes=FALSE,
xlim=extendrange(ig[,1]),
ylim=extendrange(ig[,2]))
plot(ig,
layout=layout_as_tree(ig,root=1),
vertex.shape="rectangle",
vertex.size=(strwidth(V(ig)$name) + strwidth("oo")) * 100,
#vertex.size2=strheight("I") * 2 * 100,
edge.label=acme$Get("p",traversal = "level")[-1]
)
solution with as.igraph()

Large data.tree causes plot() to error

I'm trying to build an org chart from a data.frame in r using the data.tree package.
As far as i can tell i have constructed the tree correctly, but when I try to plot() the data.tree object (which print()s fine) I get an error:
abort(0) at jsStackTrace#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:5:22110
stackTrace#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:5:22258
abort#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:28:10656
nullFunc_iii#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:5:662065
a8#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:21:31634
iC#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:9:83383
aD#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:9:102098
uF#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:9:173805
pG#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:9:204484
xc#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:11:740
http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:28:403
ccallFunc#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:5:15982
http://localhost:30899/session/viewhtml2fdc215a4edd/lib/viz-0.3/viz.js:47:42
renderValue#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/grViz-binding-0.8.4/grViz.js:38:27
http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:625:30
forEach#[native code]
forEach#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:55:21
http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:551:14
forEach#[native code]
forEach#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:55:21
staticRender#http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:549:12
http://localhost:30899/session/viewhtml2fdc215a4edd/lib/htmlwidgets-0.7/htmlwidgets.js:638:38
Any ideas?
I have just started using the data.frame package a couple of days ago, but came across the same problem with some of my trees - print(tree) worked but plot(tree) gave a similar error message to yours. So far, I could always resolve the issue by removing special characters like single and double quotation marks from the input data. Thus, the plot function appears to be sensitive to certain symbols or special characters ... maybe a starting point for your search for a solution?

No visible binding for global variable Note in R CMD check

I noticed in checking a package that I obtain notes "no visible binding for global variable" when I use functions like subset that use verbatim names of list elements as arguments.
For example with a data frame:
foo <- data.frame(a=c(TRUE,FALSE,TRUE),b=1:3)
I can do silly things like:
subset(foo,a)
transform(foo,a=b)
Which work as expected. The R code check in R CMD however doesn't understand that these refer to elements and complains about there not being any visible bindings of global variables.
While this works ok, I don't really like having notes in my package and prefer for it to pass the check with no errors, warnings and notes at all. I also don't really want to rework my code too much. Is there a way to write these codes so that it is clear the arguments do not refer to global variables?
To get it past R CMD check you can either :
Use get("b") (but that is onerous)
Place a=b=NULL somewhere higher up in your function (that's what I do)
There was a thread on r-devel a while ago where somebody from r-core basically said (from memory) "NOTES are ok, you know. The assumption is that the author checked it and is ok with the NOTE.". But, I agree with you. I do prefer to have CRAN checks return a clean "OK" on all platforms. That way the user is left in no doubt that it passes checks ok.
EDIT :
Here is the r-devel thread I was remembering (from April 2010). So that appears to suggest that there are some situations where there is no known way to avoid the NOTE, but that's ok.
This is one of the potential "unanticipated consequences" of using subset non-interactively. As it says in the Warning section of ?subset:
This is a convenience function intended for use interactively. For
programming it is better to use the standard subsetting functions like
‘[’, and in particular the non-standard evaluation of argument
‘subset’ can have unanticipated consequences.
From R version 2.15.1 onwards there is a way around this:
if(getRversion() >= "2.15.1") utils::globalVariables(c("a", "othervar"))
As per the warning section of ?subset it is better to use subset interactively, and [ for programming.
I would replace a command like
subset(foo,a)
with
foo[foo$a]
or if foo is a dataframe:
foo[foo$a, ]
you might also like to use with if foo is a dataframe and the expression to be evaluated is complex:
with(foo, foo[a, ])
I had this issue and traced it to my ggplot2 section.
This code provided the error:
ggplot2::ggplot(data = spec.df, ggplot2::aes(E.avg, fraction)) +
ggplot2::geom_line() +
ggplot2::ggtitle(paste0(title))
Adding the data name to the parameters eliminated the not:
ggplot2::ggplot(data = spec.df, ggplot2::aes(spec.df$E.avg, spec.df$fraction)) +
ggplot2::geom_line() +
ggplot2::ggtitle(paste0(title))

Resources