I am trying to post a table to my wordpress site using knit2wp. The table is created using kable and works fine. However, when I use the kableExtra package, and then knit2wp, the following line of text is added to my wordpress site:
<?xml version=“1.0” encoding=“UTF-8”?>
This line doesn't appear in the html output; only on the website.
I am looking to copy a function as per:
http://dwoll.de/rexrepos/posts/rerWorkflowWP.html
Then integrate the XML function:
post.content <- xmlOutputBuffer(header = NULL)
Or:
post.content <- xmlOutputDOM(xmlDeclaration = NULL)
Adding either of these will remove the heading, but also the tables. I am obviously new to XML. So looking for another solution.
Update:
Used xml2 to read the html output of knit2html. Then used the following functions:
xyz <- read_html("htmloutput.html")
x <- xml_find_all(xyz,".//p")
xml_remove(x, free = TRUE)
Saved as new html file, which I then entered into function as per link above.
Related
I have a R variable containing some html content inside, for exemple :
myvar = "<h3>Section Title</h3>"
I would like to print it not as <h3>Section Title</h3> but as a formated h3 title in html or markdown that jupyter notebook understands.
I have been looking a bit everywhere and found htmlwidget or knitr but I feel like it needs a HTML file. What I would like to do is just displaying a variable.
I have tried also with htmltools package and the HTML() function, but no success...
myvar = "<h3>Section Title</h3>"
# I would expect that I can do something like:
print(HTML(myvar), format='html')
# But it doesn't work, I just get:
# => <h3>Section Title</h3>
And to be very clear, the goal is also that when I save the notebook as HTML or as PDF, the html is displayed formatted (and not as raw text)
In Fine the goal is to display the citations for loaded packages, in a aesthetic way. I know that I can use print(citation("packagename"), style='html') to output it as HTML but I can't find how to format the HTML properly. That's the reason my idea is to capture this output in a variable and output it as formatted HTML.
So I found the simplest option (I think) which doesn't require any other packages than htmltools which I think is by default installed.
How to display and format HTML in R
The key is the function htmlTemplate(text_ = var) :
myvar ="<h3>Test Title</h3>"
htmlTemplate(text_ = var)
This will be displayed as raw HTML in the console, but on a Jupyter Notebook it will be displayed formatted. I didn't Try it on RStudio but I would expect it to be displayed correctly as well (anyone to confirm ?)
Another solution to display the html content (as mentionned by #krassowski) Nevertheless this works only in Jupyter Notebook.
# We still need to call `HTML()` function inside
IRdisplay::display_html( HTML(myvar) )
How to pretty print citations for loaded packages in R
My final goal was to display the citations for loaded R packages in HTML
Using the .packages() I could retrieve the list of attached packages.
Then I loop on the list and for each package name (str) I can call citation(package) on the top. To get it as html I only found the print(citation(package), style='html').
Then we need to capture the output of this into a variable. The function capture.output(func) do the trick. See below:
library('htmltools')
# Create a function to output the html of all packages
list_pkgs_html = function(){
# Remove warning for the time of the function
w = getOption("warn")
options(warn = -1)
# For each package loaded
for (p in .packages()){
# Catch error in case there is no citation for one of them.
tryCatch({
# Display the name of the package as a title h3
cat("<h3>", p, '</h3>\n')
# Print the citation in html style
print(citation(p), style = "html")
})
}
# Restore the warning as before
options(warn = w)
}
# Call the function and capture the output to a variable.
capture.output(list_pkgs_html()) -> myvar
# Display the html result.
htmlTemplate(text_ = myvar)
Output:
I have never worked with APIs so this is my first try, I don't even know if what I'm trying to do is possible.
I'm trying to obtain pictures of cells from the SwissBioPics API (https://www.npmjs.com/package/%40swissprot/swissbiopics%2Dvisualizer) and have them in my R session.
res <- httr::GET('https://www.swissbiopics.org/static/swissbiopics.js',
query = list(taxisid = '9606', sls= 'SL0073',gos = '0005641'))
result <- httr::content(res$content)
but I'm getting this error:
Error in httr::content(res$content) : is.response(x) is not TRUE
Any clues?
After many misadventures, I have your answer as promised!
Since it involves interactive imagery, courtesy of JavaScript and HTML, this solution must be run as a .Rmd file within RStudio. The interactive imagery can also be accessed in the eponymous .html file, output by knitr when you click the Knit button in RStudio.
Step 1: Project Setup
Create a new R project my_pics in RStudio, under a new directory. From within this project, create a new R Notebook (here my_book.Rmd), which should end up right next to my_pics.Rproj under the aforementioned directory.
Step 2: Supporting Files
Under that same directory, create a ./snippets subdirectory. The latter should contain the following two .txt files, copied (and corrected) from the swissbiopics-visualizer documentation:
templates.txt: the first code block given in the documentation. Reproduced here with necessary EOF and syntactically corrected comments:
<template id="sibSwissBioPicsStyle">
<style>
ul > li > a {
font-style:oblique;
}
ul.notpresent li > .subcell_description {
display:none;
}
</style>
</template>
<template id="sibSwissBioPicsSlLiItem">
<li class="subcellular_location">
<a class="subcell_name"></a> <!-- the class name is required and textContent will be set on it -->
<span class="subcell_description"></span> <!-- the class name is required and textContent will be set on it -->
</li>
</template>
custom_element.txt: the third code block given in the documentation. Reproduced here with necessary EOF:
<script type="module" src="https://www.swissbiopics.org/static/swissbiopics.js"></script>
<script defer>
if (! window.customElements.get("sib-swissbiopics-sl"))
window.customElements.define("sib-swissbiopics-sl", SwissBioPicsSL);
</script>
Mind you, these .txt files can just as easily be saved as .html files. Only the file extensions would need to be refactored, in the default values for the templates and custom_element parameters, for the make_html() function in the my_book.Rmd code below.
Step 3: Interact in RStudio
Now we are ready! In my_book.Rmd, write the following:
---
title: "R Notebook"
output: html_document
---
```{r}
library(htmltools)
library(readr)
library(rlang)
```
# Functions #
Here are the functions that do the trick. The snippets used by `make_html()` are copied from the [documentation](https://www.npmjs.com/package/%40swissprot/swissbiopics-visualizer#usage) for `swissbiopics-visualizer`, and (after fixing the HTML comments) pasted into `.txt` files (`templates.txt` and `custom_element.txt`) under the `./snippets` subdirectory, which lies within the directory containing this `.Rproj`.
```{r}
# Create comma-separated list from vectorized (or listed) items, safely escaped.
csl <- function(items) {
return(paste("\"", paste(htmltools::htmlEscape(unlist(items)), collapse = ",", sep = ""), "\"", sep = ""))
}
# Create the HTML for the interactive imagery given by the parameters. Assembly
# process is as described the documentation for 'swissbiopics-visualizer':
# https://www.npmjs.com/package/%40swissprot/swissbiopics-visualizer#usage
make_html <- function(# The NCBI taxonomy ID.
tax_id,
# The IDs of the cellular elements to highlight.
sl_ids,
# The filepath to (or raw HTML text of) the templates
# snippet.
templates = "./snippets/templates.txt",
# The filepath to (or raw HTML text of) the custom element
# snippet.
custom_element = "./snippets/custom_element.txt",
# Further arguments to 'readr::read_file()', which might
# be useful to process snippet encodings across platforms.
...) {
# Escape any strings supplied.
tax_id <- csl(tax_id[1])
sl_ids <- csl(sl_ids)
# Compile all the HTML snippets into a list:
elements <- list()
# Include the templates (as read)...
elements$templates <- readr::read_file(file = templates, ...)
# ...then include the line (created here) to target the right picture...
elements$identifier <- "<sib-swissbiopics-sl taxid=%s sls=%s></sib-swissbiopics-sl>"
elements$identifier <- sprintf(fmt = elements$identifier, tax_id, sl_ids)
# ...and finally include the definition (as read) for the custom element.
elements$custom_element <- readr::read_file(file = custom_element, ...)
# Append these snippets together, into the full HTML code.
return(paste(unlist(elements), collapse = "\n"))
}
# Display the interactive imagery given by the parameters, visible in both
# RStudio (crowded) and the R Markdown file (well laid out).
visualize <- function(# The NCBI taxonomy ID.
taxid = "9606",
# A list (or vector) of the UniProtKB subcellular location
# (SL) IDs for the cellular elements to highlight.
sls = list("SL0073"),
# Further arguments to 'make_html()'.
...
) {
# Embed the HTML text where this function is called.
return(htmltools::HTML(make_html(tax_id = taxid, sl_ids = sls, ...)))
}
```
# Results #
Here we `visualize()` the **interactive** image, also accessible on [SwissBioPics](https://www.swissbiopics.org):
```{r}
visualize(sls = list("SL0073", "SL0138"))
```
Note
Observe how (in this case) we "lazily" use the default value ("9606") for taxid, without having to specify it. Observe also how we can simultaneously highlight not one but multiple separate components, namely the Contractile vacuole ("SL0073") and the Cell cortex ("SL0138").
Now below that last chunk where visualize() is called
```{r}
visualize(sls = list("SL0073", "SL0138"))
```
you will see interactive output that looks like this:
Sadly, it appears extremely crowded in RStudio, and an HTML wizard might be needed to alter the supporting .txt (or .html) files, to achieve properly formatted HTML within this IDE.
Step 4: Embed in Reports
As with any .Rmd file, RStudio gives you the option to Knit the Markdown results into a .html file, which can be easily accessed and beautifully formatted as a report!
With my_book.Rmd open in RStudio, click the Knit button, and my_book.html should appear within that same directory. You can open this .html file in a web browser (I used Chrome) to see it in all its glory!
In Conclusion
With either of these two interactive images, you can hover to highlight the various components and layers of the diagram. Furthermore, clicking on any definition will take you by hyperlink to its profile on UnitProt.
Many of the remaining limitations are due to the swissbiopics-visualizer API itself. For example, there seems to be a malfunction in its mapping from GO IDs to SL IDs, via this dataset. As such, you should provide only SL codes to visualize().
That said, if you can wrangle that HTML and bend its layout to your will, the sky is the limit!
Enjoy!
Bonus
Here's a demo of the same interactive output, embedded right here in Stack Overflow! Unfortunately, it's unstable and horribly unwieldy in this environment, so I've left it as a mere "footnote":
<template id="sibSwissBioPicsStyle">
<style>
ul > li > a {
font-style:oblique;
}
ul.notpresent li > .subcell_description {
display:none;
}
</style>
</template>
<template id="sibSwissBioPicsSlLiItem">
<li class="subcellular_location">
<a class="subcell_name"></a> <!-- the class name is required and textContent will be set on it -->
<span class="subcell_description"></span> <!-- the class name is required and textContent will be set on it -->
</li>
</template>
<sib-swissbiopics-sl taxid="9606" sls="SL0073,SL0138" ></sib-swissbiopics-sl>
<script type="module" src="https://www.swissbiopics.org/static/swissbiopics.js"></script>
<script defer>
if (! window.customElements.get("sib-swissbiopics-sl"))
window.customElements.define("sib-swissbiopics-sl", SwissBioPicsSL);
</script>
You have to call the content-function on res, not res$content. Then you get raw content which needs to be converted e.g. via
base::rawToChar(content(res))
which results in a string containing some JS-code
base::rawToChar(content(res))
[1] "var SwissBioPics;SwissBioPics=(()=>....
I have only quickly looked at the website, but what about just downloading the files? It also goes through the API.
qurl = "https://www.swissbiopics.org/api/image/Chlamydomona_cells.svg"
fl = file.path(tempdir(), basename(qurl))
download.file(qurl, fl)
Once on disk, you can load the image in R, e.g. through the magick-package:
require(magick)
img = image_read_svg(fl)
print(img)
I often need to do a quick share of a table into an email or to a word or google document. I use the package clipr and built a function like this to put stuff on my clipboard:
function (x = .Last.value)
{
clipr::write_clip(x)
message("Value copied to clipboard")
}
When I do this with a table and paste it into the things mentioned above, the spacing is all messed up when it goes to a plain text editor (ie Spark, my email client) or to an editor that has table functionality (MS Word / Google Docs).
Is there a way to do an easy copy paste that preserves the table spacing for plain text? Or formats as a table in word/gdocs?
I regularly use the function below which elikesprogramming mentions in his answer on this question (How to solve "clipboard buffer is full and output lost" error in R running in Windows?) and it appears as a table object when pasting into Excel, Word or Outlook.
write.table(data, "clipboard-16384", sep = "\t", row.names = FALSE, quote = FALSE)
I am using blogdown to to create a blogpost that has a series of tables. Creating a single table using the kable function works fine. If you do
blogdown::new_site()
blogdown::new_post("test", ext = ".rmd")
A new rmd file will be created within the content/post directory of the project. If you open that file and create a single table by doing
```{r test1}
library(knitr)
library(magrittr)
library(shiny)
data.frame(a= c(1,2,3)) %>% kable(caption = 'test',format = 'html')
```
A correctly formatted table will be generated. The caption will read "
Table 1: test" If you look at the code of the generated site, the caption will look like this.
<caption>
<span id="tab:test1">Table 1: </span>test
</caption>
Ideally I don't have any desire to label the table as Table 1 in the first place but that is another question. If formatting of captions by kable can be disabled entirely, I'd also be happy.
However if I use lapply to generate 2 tables instead
```{r test2}
lapply(1:2,function(x){
data.frame(a= c(1,2,3)) %>% kable(caption = 'test2',format = 'html') %>% HTML()
}) -> tables
tables[[1]]
tables[[2]]
```
The captions will have the prefix \#tab:test2. If you look at the caption of these tables, you'll see
<caption>(\#tab:test2)test2</caption>
The question is, why kable behaves differently when its called from a lapply compared to its behaviour outside? Note that both of these behaviours are different that its behaviour when simply knitting the file as an html_document.
I did some digging into the kable's code and found that the caption link is created by the knitr:::create_label function. Looking into this function, I saw the part that is responsible for the wrong behaviour seen with the multiple tables.
if (isTRUE(opts_knit$get("bookdown.internal.label"))) {
lab1 = "(\\#"
lab2 = ")"
}
I could not find the code, responsible for the "correct" behaviour with the single table but it seems like knitr internal options are responsible.
Ultimately the behaviour that I want is simply
<caption>test</caption>
which is the behaviour when simply knitting an html document. But I am yet to find a way to set the relevant knitr options and why are they different within the same document.
Edit: Further examination suggests that the issue isn't lapply specific. It can be replicated using a for loop or even { by itself. A complete post with all the problematic examples can be acquired from this issue on knitr's github page. This github repo includes the basic blogdown site that replicates the issue
Turns out the responsible party is not the lapply call but the HTML call at the end. It seems like the regular process by knitr in blogdown and bookdown is to have a temporary marker for the table references in the form of (\#tab:label) and replace it with the appropriate syntax later in the processing.
I was using the HTML call to be able to use the tags object in shiny/htmltools to bind the tables together. This approach seems to make the process of replacing the temporary marker impossible for reasons outside my understanding. For my own purposes I was able to remove the temporary marker all together to get rid of both malformed captions and the working-as-intended table numbers by doing
remove_table_numbers = function(table){
old_attributes = attributes(table)
table %<>% as.character() %>% gsub("\\(\\\\#tab:.*?\\)","",.)
attributes(table) = old_attributes
return(table)
}
data.frame(a= c(1,2,3)) %>% kable(caption = 'test',format = 'html') %>% remove_table_numbers
This question still would benefit from a proper explanation of the reference link placement process and if its possible to apply it to tables in HTML calls as well. But for know this solves my issue. I'll gladly switch the accepted answer if a more complete explanation appears
good day people,
I'm working on a word based reports automation task. These reports are basically some standard text, a dozen or so charts, some numeric/trend text values that I need to populated based on logic. The trend text, numeric values or charts are to be generated from backend database.
I'm able to produce a blank document with charts using database, the R packages I used are ReporteRs, RODBC, officer and corresponding dependency packages, ggplot2 for charts.
However what I would like to achieve is, have a word document template with some sort of placeholders where I can put the charts and these numeric values.
I've basic code as following
doc <- docx(title="my doc")
mychart <- ggplot(.....)
doc <- addPlot(doc, fun=print, x = mychart)
writeDoc(doc, filename)
Can anyone advise how to approach this task. I saw usage of template parameter in docx but I couldn't find suitable examples of putting values in placeholders or putting charts at particular placeholders inside Word document.
Hope I've explained it clearly, if not please let me know.
Ok I've figured out how to achieve it finally.
MS-Word allows putting placeholders in document and bookmark them so that values/data/images can be put in their place.
You can create a normal word document(not as word template) and add your static content in it along with bookmarked placeholders as per your requirements.
Please refer here to know how to add bookmarks , Word doesn't show existing bookmarks by default, to enable that go to File -> Options -> Advanced check Show bookmarks, you'll see [your_bookmark] thing in square brackets.
Next in R, try following code
doc <- docx(title="title", template="c://above_template.docx")
doc = addPlot(doc, x=myChartVariable, bookmark="your_chart_bookmark)
writeDoc(doc, "c://new_doc_file_path.docx:)
you should see new file with a chart substituted where you put its placeholder.
I would recommend using VBA for this, not R. Do some google-research on DocVariables in Word. Add some DocVariables to your Word template, keep your analytics in Excel, and then push what you have in Excel into the Word DocVariables. Use the script below, which runs in Excel, to make everything work.
Sub PushToWord()
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next
objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value
objWord.ActiveDocument.Fields.Update
'On Error Resume Next
objWord.Visible = True
End Sub
Finally, add a reference to Word, from Excel. Tools > References > Microsoft Word xxx Object Library.