Creating space under/over paragraphs, tables etc - r

I cant figure out from the officer manual or function reference, if it is possible to create space between objects in a word document? By space i mean a function that would equal pressing "enter" while writing.
Thank you in advance!

body_add_par(value="")
should do the job.
eg.
myDoc <- myDoc %>%
body_add_par(value = "example1")
body_add_par(value = "")
body_add_par(value = "example1")
You can use this to create spaces after tables and other objects.

from the documentation using /r/n will do the work . Example
ftext(", \r\nhow are you?", prop = bold_face ) )

Related

Save gt table as html w/o extra line return

I have a simple table with a link in it.
I am using gt because it does some formatting nicely, which is not shown, because it is not relevant to my question.
I wish to save the gt table as html with no tag so that it can be inserted into another html page.
Here is the gt_tbl in RStudio's Viewer. Great!
And here is the raw_html_tbl as viewed in a web browser saved using either the writeLines method or the cat method as shown in the script.
The HTML table in the browser seems to have added a line return, hence the need for the scroll bar.
How can I save the raw html file so that the scroll bar does not appear and the height of "This is a link" remains one line?
library(gt)
library(tibble)
df <- tibble(
note = c("This is a <a href = https://www.cnn.com>link</a>.")
)
gt_tbl <- gt(df) |>
tab_options(
table.width = 450
) |>
fmt_markdown(columns = note)
gt_tbl
raw_html_tbl <- gt_tbl |>
as_raw_html()
writeLines(text = raw_html_tbl, con = "test/test_tbl.html")
cat(raw_html_tbl, file = "test/test_tbl.html")

getting rmarkdown to print improved tibble printing

The pillar package offers a number of options to format tibble printing.
https://pillar.r-lib.org/reference/pillar-package.html#package-options
For example, this is what I see on my Windows machine, which supports these options:
But when I set the same options for rmarkdown document, I don't see any difference in the printed output.
Is there a way to successfully get this to work or this is not supported in rmarkdown itself?
In the vignette for the tibble package, there is a possible solution. In your setup chunk of your .Rmd file, put:
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(tibble)
set.seed(1014)
options(crayon.enabled = TRUE)
options(pillar.bold = TRUE, pillar.subtle_num = TRUE)
knitr::opts_chunk$set(collapse = TRUE, comment = pillar::style_subtle("#>"))
colourise_chunk <- function(type) {
function(x, options) {
lines <- x
if (type != "output") {
lines <- crayon::red(lines)
}
paste0(
'<div class="sourceCode"><pre class="sourceCode"><code class="sourceCode">',
paste0(
fansi::sgr_to_html(htmltools::htmlEscape(lines)),
collapse = "\n"
),
"</code></pre></div>"
)
}
}
knitr::knit_hooks$set(
output = colourise_chunk("output"),
message = colourise_chunk("message"),
warning = colourise_chunk("warning"),
error = colourise_chunk("error")
)
In a new chunk:
broom::tidy(stats::chisq.test(table(ggplot2::msleep$vore)))
My HTML output:
I'd say that from my markdown experience that Pillow will not work as markdown uses pandoc.
As alternatives, I'd recommend using the kable package for a similar look using it's themes options. A handy tutorial with using a relatively similar theme ->
https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html
Another cool option of making really cool markdown tables would be to use formattable, which has a lot of in-depth options for formatting
And a couple of handy tutorials for that ->
https://www.littlemissdata.com/blog/prettytables
https://www.littlemissdata.com/blog/pretty-r-tables-in-github
Hopefully, this helps you out.

Is it possible to programmatically export a list of networks one by one to PNG in the R package visNetwork?

I tried sample codes for visExport() and is able to add a "Export as PNG" button to a Shiny webpage. But this would need user interaction to press the button to export the network to a PNG image file.
I have over hundred of networks and would like to export them each to a PNG file. And some of these would need regular updating. So it would be logistically nice to be able to export all them to PNG files without a user pressing the "Export as PNG" button for each of the network.
So is it possible to programmatically export a list of networks one by one to PNG? This would be just like for visSave() to export the HTML for each network one by one.
In reference to other post, here is working code making use of the webshot package.
library(visNetwork)
library(tidyverse)
library(webshot)
# create network data
nodes = data.frame(id = numeric(),label=character(),set = numeric(),stringsAsFactors = F)
edges = data.frame(from = numeric(),to = numeric(),set = numeric(),stringsAsFactors = F)
for (i in 1:10){
tempNodes <- data.frame(id = 1:15, label = paste("Label", 1:15), set = i)
tempEdges <- data.frame(from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1, set = i)
nodes = rbind(nodes,tempNodes)
edges = rbind(edges,tempEdges)
}
# loop through each set to export to PNG
for (i in 1:max(nodes$set)){
subNodes = nodes[nodes$set==i,]
subEdges = edges[edges$set==i,]
network = visNetwork(subNodes, subEdges, width="100vw",height = "100vh") %>%
visLayout(randomSeed=1,improvedLayout=TRUE) %>%
visGroups(groupname = "actorImported",shape="circle") %>%
visEdges(smooth=FALSE) %>%
visPhysics(solver = "barnesHut")
fname = paste0("network",sprintf("%03d",i),".html")
visSave(network,fname)
webshot(fname,delay=0.5,zoom=2,file=paste0("network",sprintf("%03d",i),".png"),
vwidth=900,vheight=900)
}
The short answer must be "Yes", but since you've not given us any sample code, it's impossible to give you a tested solution. But you say you have a hundred networks. Let's assume there in a vector networks. (A list would work as well with minor changes to the sample code below.) You can export one graph using a Shiny button. So you must have code to create a single network image. Suppose that's in a function createImageForNetwork(x), where x is a network. You'll also need a function to create an output file name for each image. Suppose that's called getFilename(x). Then something like the untested code below will do what you want:
exportNetworkImage <- function(x) {
png(getFilename(x))
createImageForNetwork(x)
dev.off()
}
lapply(1:length(networks), function(x) exportNetworkImage(networks[x]))
If you want to do that with a single button click in your Shiny app, then just put that code inside the button's observeEvent handler.

R: Insert table in template table using ReporteRs

I am in the process of making a dashboard. Basically, I am pulling out selected information from a database that I then want to display in a word template. I set up the template with a table (2 rows, 3 columns). In each cell I put a bookmark. Then, using the R package ReporteRs I put specific information from R into a cell within the template based on the bookmark.
ISSUE: I cant seem to insert tables into a cell of the template.
Tried: I thought it might be due to size of the table (as i experienced that size was the issue when inserting figures), but this is not the case.
Below is an example with the error. In order to run this you have to create a Word document with a table with a bookmark in one of the cells called 'test'.
doc = docx( title = "Dashboard",template="H:\\test.docx")
myt <-FlexTable(cars[c(1:10),])
doc <-addFlexTable(doc,myt,bookmark="test")
writeDoc(doc, "H:\\testresult.docx")
If you then create a bookmark outside of the table and assign the table to the new bookmark, it seems to work.
Does anyone know how to insert a table (data frame as a table) into any cell of my template?
If argument bookmark is used, content (plots, paragraphs or images) will replace the whole paragraph containing the bookmark.
Behavior is different for tables: tables are added after the paragraph that contains the bookmark. A workaround is to add a paragraph after the bookmarked paragraph in the cell of the template. Then use deleteBookmark to delete the paragraph containing the bookmark.
doc <- docx( title = "Dashboard",template="H:\\test.docx")
myt <- FlexTable(cars[c(1:10),])
# make sure there is one new paragraph after the paragraph that contains 'test'
# add the FlexTable just after the paragraph containing bookmark 'test'
doc <- addFlexTable(doc,myt,bookmark="test")
# then delete the paragraph containing bookmark 'test'
deleteBookmark(doc, bookmark= "test")
writeDoc(doc, "H:\\testresult.docx")
You may use Sections with columns instead (and eventually column breaks):
doc = docx( )
doc = addSection(doc, landscape = TRUE, ncol = 2 )
doc = addPlot( doc = doc, fun = function() {
barplot( 1:8, col = 1:8 )
}, width = 3, height = 3, pointsize = 5)
doc = addColumnBreak(doc )
doc = addFlexTable(doc, FlexTable(head(iris) ) )

Is it possible to view an HTML table in the viewer pane?

I would like to know if there is any function which makes it easy to visualize an html object in the RStudio's viewer pane. For instance, I would like to know if it would be possible to view an html table in the viewer pane.
library("Quandl")
library("knitr")
df <- Quandl("FBI_UCR/USCRIME_TYPE_VIOLENTCRIMERATE")
kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")
I have a solution that works for kable tables.
kable(iris) %>% kableExtra::kable_styling()
This is automatically displayed in the viewer pane. No need for tempfile.
I have this functionality in my htmlTable package and the function is rather simple:
print.htmlTable<- function(x, useViewer = TRUE, ...){
# Don't use viewer if in knitr
if (useViewer &&
!"package:knitr" %in% search()){
htmlFile <- tempfile(fileext=".html")
htmlPage <- paste("<html>",
"<head>",
"<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">",
"</head>",
"<body>",
"<div style=\"margin: 0 auto; display: table; margin-top: 1em;\">",
x,
"</div>",
"</body>",
"</html>", sep="\n")
cat(htmlPage, file=htmlFile)
viewer <- getOption("viewer")
if (!is.null(viewer) &&
is.function(viewer)){
# (code to write some content to the file)
viewer(htmlFile)
}else{
utils::browseURL(htmlFile)
}
}else{
cat(x)
}
}
RStudio recommends that you use the getOption("viewer") instead of #Ramnath's suggestion, the raw RStudio::viewer(). My solution also adds the utils::browserURL() in case you are not using RStudio. I got the idea from this blog post.
Here is a quick way to do this in RStudio
view_kable <- function(x, ...){
tab <- paste(capture.output(kable(x, ...)), collapse = '\n')
tf <- tempfile(fileext = ".html")
writeLines(tab, tf)
rstudio::viewer(tf)
}
view_kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")
If the kable function can return an object of class kable, then one could rename view_kable as print.kable in which case merely calling the kable function would open the table in the viewer. If you think this is useful, please go ahead and file a feature request on the knitr github page.
As was explained on this RStudio Support page, the key is to use tempfile() :
Note that the Viewer pane can only be used for local web content. This
content can either be static HTML files written to the session
temporary directory (i.e. files with paths generated by the tempfile
function) or a locally run web application.
See my answer to this question for a bare-bones example.
For kable objects, we can use print.kableExtra
library(knitr)
x <- kable(head(iris), format = "html")
library(kableExtra)
class(x) <- c("kableExtra", class(x))
print(x)

Resources