Flextable : using superscript in the dataframe - html

This question was asked few times, but surprinsingly, no answer was given.
I want some numbers in my dataframe to appear in superscript.
The functions compose and display are not suitable here since I don't know yet which values in my dataframe will appear in superscript (my tables are generated automatically).
I tried to use ^8^like for kable, $$10^-3$$, paste(expression(10^2)), "H\\textsubscript{123}", etc.
Nothing works !! Help ! I pull out my hair...
library(flextable)
bab = data.frame(c( "10\\textsubscript{-3}",
paste(as.expression(10^-3)), '10%-3%', '10^-2^' ))
flextable(bab)
I am knitting from Rto html.

In HTML, you do superscripts using things like <sup>-3</sup>, and subscripts using <sub>-3</sub>. However, if you put these into a cell in your table, you'll see the full text displayed, it won't be interpreted as HTML, because flextable escapes the angle brackets.
The kable() function has an argument escape = FALSE that can turn this off, but flextable doesn't: see https://github.com/davidgohel/flextable/issues/156. However, there's a hackish way to get around this limitation: replace the htmlEscape() function with a function that does nothing.
For example,
```{r}
library(flextable)
env <- parent.env(loadNamespace("flextable")) # The imports
unlockBinding("htmlEscape", env)
assign("htmlEscape", function(text, attribute = FALSE) text, envir=env)
lockBinding("htmlEscape", env)
bab = data.frame(x = "10<sup>-3</sup>")
flextable(bab)
```
This will display the table as
Be careful if you do this: there may be cases in your real tables where you really do want HTML escapes, and this code will disable that for the rest of the document. If you execute this code in an R session, it will disable escaping for the rest of the session.
And if you were thinking of using a document like this in a package you submit to CRAN, forget it. You shouldn't be messing with bindings like this in code that you expect other people to use.
Edited to add:
In fact, there's a way to do this without the hack given above. It's described in this article: https://davidgohel.github.io/flextable/articles/display.html#sugar-functions-for-complex-formatting. The idea is to replace the entries that need superscripts or subscripts with calls to as_paragraph, as_sup, as_sub, etc.:
```{r}
library(flextable)
bab <- data.frame(x = "dummy")
bab <- flextable(bab)
bab <- compose(bab, part = "body", i = 1, j = 1,
value = as_paragraph("10",
as_sup("-3")))
bab
```
This is definitely safer than the method I gave.

Related

HTML Dec Code image in Tkinter label — either text or image is doubled

I'd like to add a picture to some of my tkinter labels, and I found a page with many of them (there are, of course, many similar pages), including some that I want.
But I'm having a strange behavior with this.
The code
import tkinter as tk
from tkinter import ttk
import html
root = tk.Tk()
root.geometry("200x100")
s = html.unescape('&#127937') # chequered flag
text = "some text"
label_text = "{}{}".format(text, s)
my_label = ttk.Label(root, text=label_text)
my_label.pack()
t = chr(9917)
another = "football ball"
another_text = "{}{}".format(t, another)
another_label = ttk.Label(root, text=another_text)
another_label.pack()
root.mainloop()
produces the following window:
On the other hand, if I replace label_text = "{}{}".format(text, s) with label_text = "{}{}".format(s, text) the flag appears twice instead (once before "some text" and another after).
Apparently this only happens with html images.
For example, with the second label, I have the expected behavior.
Is there something I'm doing wrong here, or should I just avoid these images in tkinter?
i wouldnt avoid them yet i wouldnt advise them either. Because tkinter propbably uses regular images its propbably not used to emojis. My recommendation is to use regular images instead of emojis.

RSelenium: input value in text box

I'm looking to use RSelenium to input some gene names into an online repository that creates a functional annotation heatmap for said genes.
However, I'm struggling to work out how to input the gene list into the text box to generate the heatmap.
Here is an image of the text box and the html associated with it.
The code I have so far (see below) can navigate successfully to the appropriate page, and select the appropriate text box but I can't work out how to input the text such that the list of genes at the bottom of the html code is added to as if I was typing the genes in manually. Note, the genes you can see in text box in the image were input manually.
##### Load driver and navigate to site #####
driver <- rsDriver(browser=c("chrome"), chromever="80.0.3987.106")
remDr <- driver[["client"]]
remDr$navigate("http://solo.bmap.ucla.edu/shiny/webapp/")
## Select heatmap option
gene_toggle <- remDr$findElement(using = 'css', '[class="dropdown-toggle"]')
gene_toggle$clickElement()
input <- remDr$findElement(using = 'css', '[data-value="panel-Heatmap"]')
input$clickElement()
## Input gene list to text box - not working yet - can't get text to enter properly
gene_select <- remDr$findElement(using = 'css', '[class="selectize-input items not-full has-options has-items"]')
gene_select$clickElement()
##### NOTE I HAVE TRIED THESE OPTION BELOW ....
gene_select$sendKeysToElement("NEUROD1")
gene_select$sendKeysToElement(list("NEUROD1"))
gene_select$sendKeysToElement(list("NEUROD1", key = "enter"))
gene_select$sendKeysToElement(list("NEUROD6, NEUROD2"))
I feel like I'm almost there, but unsure if I'm selecting the wrong element or formatting the sendKeysToElement command wrongly. I'm fairly new to RSelenium.
Any advice would be greatly appreciated.
You're almost there indeed, just need to select the <input> element inside your gene_select:
input <- gene_select$findChildElement(using = 'xpath', value = 'input')
input$sendKeysToElement(list("NEUROD2", key = "enter"))

Table way too wide to fit in Markdown generated PDF

I am trying to display a table from an SQL query to a pdf by using Rmarkdown. However, the table I get is too wide and it does not fit in the document.
I have been recommended to use the Pander package, and so I tried to use the pandoc.table() function which works greatly on the console, but for some reason it stops my document from rendering in Rmarkdown.
The code looks kinda like this :
rz = dbSendQuery(mydb, "select result.id result_id, company.id company_id, (...)")
datz = fetch(rz, n=-1)
It is a very long query but, as I said, it works both on MySQL and R console (working on RStudio).
So, when I do
kable(datz, "latex", col.names = c(colnames(datz)), caption=paste('This is a sample table')) %>% kable_styling(latex_options = "striped") %>% column_spec(1, bold = T, color = "red"))
the results that get printed are too wide to fit in the PDF.
I do not know how can I solve this. I tried with pandoc.tables() from pander package, but the format of the result seems to be very humble compared to the options I have in kable.
You have to use the scale_down option from kableExtra. The scale_down option is going to fit your table on one page when it is too wide. The police font will also be reduce.
Here is an example of the code you could use :
kable(your_dt, "latex", booktabs = T) %>%
kable_styling(latex_options = c("striped", "scale_down"))

as3 - detect urls in dynamic text and make them links

Anyone know of any good classes or functions that will do this? I've found some regexes but what I need is to pass the string to a method and have it return the same string, but with urls turned blue and turned into hyperlinks. Seems like a fairly common task, but I can't find anything.
EDIT - the following works for any link starting with http:
var myPattern:RegExp = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
var str = text.replace(myPattern, "<font color='#04717D'><a target='_blank' href=\"$&\">$&</a></font>");
field.htmlText = str;
But it doesn't work for links that start with "www", because the href ends up looking like this:
www.google.com
Would love to know how to fix that.
I'm wary of making the existing regular expression/ replacement call any more complicated. With that in mind the most straightforward way of doing this is probably to write a second regular expression to correct any bad tags in the output from the first. I'd also add a 'g' to the end of your main regular expression so that it captures multiple URLs in the text
So, your main regular expression would now look like this:
var mainPattern:RegExp = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
Your secondary regular expression will look something like this:
var secondaryPattern:RegExp = /\"www/g;
it should capture any links that don't start with "http:"
You then run both these expressions over your input string replacing as necessary:
var someText:String = "This is some text with a link in it www.stackoverflow.com and also another link http://www.stackoverflow.com/questions/5239966/as3-detect-urls-in-dynamic-text-and-make-them-links";
someText = someText.replace(mainPattern, "<a target='_blank' href=\"$&\">$&</a>");
someText = someText.replace(secondaryPattern, "\"http://www");

R Markdown HTML Number Figures

Does anyone know how to number the figures in the captions, for HTML format R Markdown script?
For PDF documents, the caption will say something like:
Figure X: Some Caption Text
However, the equivalent caption for the HTML version will simply say:
Some Caption Text
This makes cross-referencing figures by number completely useless.
Here is a minimal example:
---
title: "My Title"
author: "Me"
output:
pdf_document: default
html_document: default
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
I have tried setting toc, fig_caption and number_sections within each of the output formats, but this does not seem to change the result.
The other answers provided are relatively out of date, and this has since been made very easy using the bookdown package. This package provides a number of improvements which includes the built-in numbering of figures across Word, HTML and PDF.
To be able to use bookdown, you need to first install the package install.packages("bookdown") and then use one of the output formats. For HTML, this is html_document2. Taking your example:
---
title: "My Title"
author: "Me"
date: "1/1/2016"
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
These Figures will be numbered Figure 1 and Figure 2. Providing the code chunk is named and has a caption, we can cross reference the output using the the syntax \#ref(fig:foo) where foo is the name of the chunk i.e. \#ref(fig-cars). You can learn more about this behaviour here
Further Reading
R Markdown: The definitive Guide: Chapter 11 provides a great overview of bookdown
Authoring books with bookdown provides a comprehensive guide on bookdown, and recommended for more advanced details.
So unless someone has a better solution, this is the solution that I came up with, there are some flaws with this approach (for example, if the figure/table number is dependent on the section number etc...), but for the basic html document, it works.
Somewhere at the top of you document, run this:
```{r echo=FALSE}
#Determine the output format of the document
outputFormat = opts_knit$get("rmarkdown.pandoc.to")
#Figure and Table Caption Numbering, for HTML do it manually
capTabNo = 1; capFigNo = 1;
#Function to add the Table Number
capTab = function(x){
if(outputFormat == 'html'){
x = paste0("Table ",capTabNo,". ",x)
capTabNo <<- capTabNo + 1
}; x
}
#Function to add the Figure Number
capFig = function(x){
if(outputFormat == 'html'){
x = paste0("Figure ",capFigNo,". ",x)
capFigNo <<- capFigNo + 1
}; x
}
```
Then during the course of your document, if say you want to plot a figure:
```{r figA,fig.cap=capFig("My Figure Caption")
base = ggplot(data=data.frame(x=0,y=0),aes(x,y)) + geom_point()
base
```
Substitute the capFig to capTab in the above, if you want a table caption.
We can make use of pandoc-crossref, a filter that allows a cross-referencing of figures, tables, sections, and equations and works for all output format. The easiest way is to cat the figure label (in the form of {#fig:figure_label}) after each plot, although this requires echo=FALSE and results='asis'. Then we can reference a figure as we would a citation : [#fig:figure_label] produces fig. figure_number by default.
Here is a MWE:
---
output:
html_document:
toc: true
number_sections: true
fig_caption: true
pandoc_args: ["-F","pandoc-crossref"]
---
```{r}
knitr::opts_chunk$set(echo=FALSE,results='asis')
```
```{r plot1,fig.cap="This is plot one"}
x <- 1:10
y <- rnorm(10)
plot(x,y)
cat("{#fig:plot1}")
```
As we can see in [#fig:plot1]... whereas [#fig:plot2] shows...
```{r plot2, fig.cap="This is plot two"}
plot(y,x)
cat("{#fig:plot2}")
```
which produces (removing the graphics
PLOT1
Figure 1: This is plot one
As we can see in fig. 1… whereas fig. 2 shows…
PLOT2
Figure 2: This is plot two
See the pandoc-crossref readme for more options and customizations.
To install pandoc-crossref, assuming you have a haskell installation:
cabal update
cabal install pandoc-crossref
I solve cross-referencing using a solution similar to that posted by Nicholas above. I use bookdown for some projects but I find that awkward to use for other projects where I just want simple cross-referencing.
I use the following when I am writing a paper with rmarkdown and I want it in standard format for submission to a journal. I want a figure legend at the end, then tables, then I'll have the tables and figures. As I am writing, I only have a rough idea of what order the figures will be referenced in the text. I just want to reference them with a text code like fig:foobar and have the number assigned based appearance in the text. When I look at the figure legend list, I'll see what order to put the legends and will move legends around as needed.
Here's my structure.
I have an R package where I have things I need for papers, like various bibliographies and helper R functions. In that package, I have the following function which uses some variables defined in the main Rmd environment: .rmdenvir and .rmdctr .
ref <- function(useName) {
require(stringr)
if(!exists(".refctr")) .refctr <- c(`_` = 0)
if(any(names(.refctr)==useName)) return(.refctr[useName])
type=str_split(useName,":")[[1]][1]
nObj <- sum(str_detect(names(.refctr),type))
useNum <- nObj + 1
newrefctr <- c(.refctr, useNum)
names(newrefctr)[length(.refctr) + 1] <- useName
assign(".refctr", newrefctr, envir=.rmdenvir)
return(useNum)
}
It assumes that I name things I want referenced with something like cntname:foo, for example fig:foo. It makes a new counter for each one and I can make up new counters on the fly (while writing) if needed.
In my main Rmd file, I have some set-up lines:
```{r setup_main}
require(myPackageforPapers)
# here is where the variables needed by ref() are defined.
.rmdenvir = environment()
.refctr <- c(`_` = 0)
````
In the text I use the following
You can see what I am trying to show in Figure `r ref("fig:foo")`
and you can see it also in Tables `r ref("tab:foo")`
and A`r ref("tabappA:foobig")`.
to get "You can see what I am trying to show in Figure 1 and you can see it also in Tables 1 and A1." Although the numbers might not be 1; the number to use will be dynamically determined. I don't have to use a special function for the first time I reference a figure, table or whatever I am counting. ref() figures that out by looking to see if the label exists already. If not it assigns the next number, and returns it. So you don't have to use "label" in one place and "ref" in another.
In the course of writing, I might decide that appendix A is getting too big, and that I will split off some of the tables into an appendix B. All I need to do is change the above to
You can see what I am trying to show in Figure `r ref("fig:foo")`
and you can see it also in Tables `r ref("tab:foo")`
and B`r ref("tabappB:foobig")`.
I just specify a new counter name 'tabappB' and the numbers for that are dynamically determined.
At the end of my Rmd file, I have a figure list that will look like
# Figure Legends
Figure `r ref("fig:foo")`. This is the legend for this figure.
Figure `r ref("fig:foo2")`. This is the legend for another figure.
Then my tables appear like so
```{r print-tablefoo, echo=FALSE}
tablefoo=mtcars
thecap = "Tables appear with a legend while figures do not."
fullcap = paste("Table ", ref("tab:foo"), ". ", thecap, sep="")
kable(tablefoo, caption=fullcap)
```
and then the figures like so:
```{r fig-foo, echo=FALSE, fig.cap=paste("Figure",ref("fig:foo"))}
plot(1,1)
```
Appendix A is an Rmd file that included as a child. It will have tables like
```{r print-tableAfoo, echo=FALSE}
tablefoo=mtcars
thecap = "This is a legend."
fullcap = paste("Table A", ref("tabappA:foobig"), ". ", thecap, sep="")
kable(tablefoo, caption=fullcap)
```
I do have to add the "A" to get Table A1, but I find it easier if R doesn't think too much for me in terms of labelling my counters. I just I want it to return the right number.
The cross-referencing works for html, pdf/latex or word. I'd happily stick with latex solutions, but my co-authors use word so I need a solution that works with pandoc and word. Also sometimes I want html or some other output and I need a solution that works for any output that works with rmarkdown.