Adding flextable including images in PowerPoint - flextable

I'm trying to add a flextable object including an image to PowerPoint using officer. But the image disappears. I can reproduce the problem using the example David has posted hear
library(flextable)
library(tibble)
download.file("https://www.r-project.org/logo/Rlogo.png", destfile = "Rlogo.png")
pupil.tbl <- tribble(
~col1, ~col2, ~col3,
"A", "B", "Rlogo.png",
"C", "D", "Rlogo.png"
)
pupil.tbl <- as.data.frame(pupil.tbl)
# display only col1 and col2
pupil.ft <- flextable(pupil.tbl, col_keys = c("col1", "col2") )
add_img_to_flextable <- function(ft, i, j){
display(
ft, i=i, col_key = j, pattern = "{{att_tbl}}",
formatters = list(# use col3 even if not displayed
att_tbl ~ as_image(col3, src = col3, width = 1.29, height = 1)
)
)
}
pupil.ft <- add_img_to_flextable(pupil.ft, i = 2, j = "col2")
If I run:
print(pupil.ft,preview='html')
print(pupil.ft,preview='docx')
everything works fine, but in PPTX format the image isn't shown anymore
print(pupil.ft,preview='pptx')
Is this a known limitation of PowerPoint? Is there any workaround how to show the images inside a table?
Thanks,
Philipp

That is a known limitation of PowerPoint, it can not handle images in cells

Related

How to source a locally stored image for embedding into a table cell in R Shiny?

The below code does a terrific job of rendering a web-sourced image in a cell of the rhandsontable. However, I'd like swap that image with a jpg image I have stored on my computer. I've tried modifying the below as.character(img(src = "...")) to reflect the local directory and filename, with no luck.
Any suggestions for a straightforward way to do this?
I searched for solutions, for example, Display locally-stored image in R Shiny, but they look rather involved given what I thought is the simplicity of what I'm trying to do. Certainly accessing your local drive is easier than reaching out to the Web via API.
Here's the painfully simple image I want to upload (shrunken of course):
Code:
library(magrittr)
library(htmlwidgets)
library(rhandsontable)
library(shiny)
DF = data.frame(
Col_1 = c("Row 1"),
Col_Help = c(
as.character(img(
src = "https://images.plot.ly/language-icons/api-home/python-logo.png",
title = "My first help text",
style = "width: 50px;")
)
),
text = c("Row 1 does xxx"),
stringsAsFactors = FALSE
)
ui <- fluidPage(br(),rHandsontableOutput('my_table'))
server <- function(input, output, session) {
output$my_table <- renderRHandsontable({
rhandsontable::rhandsontable(
DF,
allowedTags = "<em><b><strong><a><big><img>"
) %>%
hot_cols(colWidths = c(200, 80)) %>%
hot_col(1:2, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
hot_cols(colWidths = ifelse(names(DF) != "text", 100, 0.1))
})
}
shinyApp(ui, server)
Put your file, say question_mark.jpg in the www folder of your shiny app, and then adjust your DF definition as below:
DF = data.frame(
Col_1 = c("Row 1"),
Col_Help = c(
as.character(img(
src = "question_mark.jpg",
title = "My first help text",
style = "width: 50px;")
)
),
text = c("Row 1 does xxx"),
stringsAsFactors = FALSE
)
Output:

R - combine image and table then export as PDF

I have four goals:
Connect to a Postgresql database and pull some data
Gloss up a table with some colour and formatting
Include an image (company logo) above it
Export as PDF
1 and 2 are easy enough and 4 seems possible even if not convenient, but I don't think R was designed to add and position images. I've attached some sample code of how I envision creating the table, and then a mockup of what I think the final version might look like. Can anyone advise on the best way to accomplish this?
Sample data:
data(mtcars)
df <- head(mtcars)
HTML approach: flexible and portable to other apps
library(tableHTML)
html_table <- df %>%
tableHTML(rownames = FALSE, border = 0) %>%
add_css_row(css = list(c('font-family', 'text-align'), c('sans-serif', 'center'))) %>%
add_css_header(css = list(c('background-color', 'color'), c('#173ACC', 'white')), headers = 1:ncol(df))
Grob approach: Creating a ggplot-like image. I've seen recommendations to use grid.arrange to place an image on top and export as a PDF
library(ggpubr)
tbody.style = tbody_style(color = "black",
fill = "white", hjust=1, x=0.9)
grob_table <- ggtexttable(df, rows = NULL,
theme = ttheme(
colnames.style = colnames_style(color = "white", fill = "#173ACC"),
tbody.style = tbody.style
)
)
grid.arrange(table_image)
You are almost there. You just need to import your image (could be png, jpeg or svg) then pass it to grid::rasterGrob. Use the options in rasterGrob to adjust size etc. Then pass your grob table to gridExtra::grid.arrange
logo_imported <- png::readPNG(system.file("img", "Rlogo.png", package="png"), TRUE)
lg <- grid::rasterGrob(logo_imported)
gridExtra::grid.arrange(lg, grob_table)
You can then either render this to pdf by adding it to an rmarkdown report (probably best), or you can save directly to pdf via
gridExtra::grid.arrange(lg, grob_table)
pdf(file = "My Plot.pdf",
width = 4, # The width of the plot in inches
height = 4)

How to save an html page that was created with `formattable` and has conditional coloring?

I used formattable package in R to create a conditionally colored table rendered in the viewer as an html page (This is the link the the forum response that helped me to do this (thanks for the responder!): How to conditionally color table elements using formattable and color_tile?). I want to save it exactly like if I click export and save as a web page within the viewer.
I am trying to save the html page seen in the Viewer window with the conditional coloring. I've tried the two solutions here but am not able to save with their colors still present:
Save View() output of RStudio as html
Save html result to a txt or html file
TLDR: I want to save the output from the code below (Credit to Ruth Gg) with the colors still present basically via code not with the click and point button within viewer.
Here is the code to make the table I am trying to save from the previous StackOverflow forum:
library(formattable)
# Set custom colors
green <- "#71CA97"
red <- "#ff7f7f"
# Make example table
col1 <- c(1.2, 4.2, 5.6, 7.1)
col2 <- c(5.0, 1.3, 10.3, 6.0)
col3 <- c(4.7, 6.3, 1.5, 6.3)
mydata <- data.frame(col1, col2, col3)
# Define color_tile_mean function
color_tile_mean <- function (...) {
formatter("span", style = function(x) {
style(display = "block",
padding = "0 4px",
`border-radius` = "4px",
`background-color` = ifelse(x < mean(x) , red, green)) # Remember to change the colors!
})}
# Use it just like color_tile but without colors
formattable(mydata, align=c("c", "c", "c"),list(
col1=color_tile_mean(),
col2=color_tile_mean(),
col3=color_tile_mean()
)
)
Here is one of the packages I tried to use:
library(formattable)
# Set custom colors
green <- "#71CA97"
red <- "#ff7f7f"
# Make example table
col1 <- c(1.2, 4.2, 5.6, 7.1)
col2 <- c(5.0, 1.3, 10.3, 6.0)
col3 <- c(4.7, 6.3, 1.5, 6.3)
mydata <- data.frame(col1, col2, col3)
# Define color_tile_mean function
color_tile_mean <- function (...) {
formatter("span", style = function(x) {
style(display = "block",
padding = "0 4px",
`border-radius` = "4px",
`background-color` = ifelse(x < mean(x) , red, green)) # Remember to change the colors!
})}
bboop <- formattable(mydata, align=c("c", "c", "c"),list(
col1=color_tile_mean(),
col2=color_tile_mean(),
col3=color_tile_mean()
))
htmlwidgets::saveWidget(widget = bboop, file = f)
#f is string of filepath
Error when trying to use htmlwidgets::saveWidget:
Error in .getNamespace(pkg) :
invalid type/length (symbol/0) in vector allocation
Does anyone have any advice? Sorry this is long. I wanted to be thorough.

Deleting commas in R Markdown html output

I am using R Markdown to create an html file for regression results tables, which are produced by stargazer and lfe in a code chunk.
library(lfe); library(stargazer)
data <- data.frame(x = 1:10, y = rnorm(10), z = rnorm(10))
result <- stargazer(felm(y ~ x + z, data = data), type = 'html')
I create a html file win an inline code r result after the chunk above. However, a bunch of commas appear at the top of the table.
When I check the html code, I see almost every </tr> is followed by a comma.
How can I delete these commas?
Maybe not what you are looking for exactly but I am a huge fan of modelsummary. I knit to HTML to see how it looks and then usually knit to pdf. The modelsummary equivalent would look something like this
library(lfe)
library(modelsummary)
data = data.frame(x = 1:10, y = rnorm(10), z = rnorm(10))
results = felm(y ~ x + z, data = data)
modelsummary(results)
There are a lot of ways to customize it through kableExtra and other packages. The documentation is really good. Here is kind of a silly example
library(kableExtra)
modelsummary(results,
coef_map = c("x" = "Cool Treatment",
"z" = "Confounder",
"(Intercept)" = "(Intercept)")) %>%
row_spec(1, background = "#F5ABEA")

How to extract input from a dynamic matrix in R shiny

This is related to an old question about creating a matrix-style input in a shiny app with dynamic dimensions. My goal is to have a matrix of numerical inputs (the dimensions of which are determined by other user inputs), and then pass that matrix to other R commands and print some output from those calculations. I have code that successfully executes everything except that I can only access the user inputs as characters.
Here is an example that sets up the input and just prints a couple cells from the matrix (this works fine, but isn't what I need):
shiny::runApp(list(
ui = pageWithSidebar(
headerPanel("test"),
sidebarPanel(
numericInput(inputId = "nrow",
label = "number of rows",
min = 1,
max = 20,
value = 1),
numericInput(inputId = "ncol",
label = "number of columns",
min = 1,
max = 20,
value = 1)
),
mainPanel(
tableOutput("value"),
uiOutput("textoutput"))
),
server = function(input,output){
isolate({
output$value <-renderTable({
num.inputs.col1 <- paste0("<input id='r", 1:input$nrow, "c", 1, "' class='shiny-bound-input' type='number' value='1'>")
df <- data.frame(num.inputs.col1)
if (input$ncol >= 2){
for (i in 2:input$ncol){
num.inputs.coli <- paste0("<input id='r", 1:input$nrow, "c", i, "' class='shiny-bound-input' type='number' value='1'>")
df <- cbind(df,num.inputs.coli)
}
}
colnames(df) <- paste0("time ",as.numeric(1:input$ncol))
df
}, sanitize.text.function = function(x) x)
})
output$textoutput <- renderUI(paste0("Cells [1,1] and [2,2]: ",input$r1c1,",",input$r2c2))
}
))
However, when I try to do any operation on the inputs in the matrix, such as output$textoutput <- renderUI(as.numeric(paste0(input$r1c1))+as.numeric(paste0(input$r2c2))), I get classic R errors like $ operator is invalid for atomic vectors. I have tried many combinations of 'as.numeric', 'as.character', ect. to try to get it into the correct format. When I check the structure of those input cells, I see that they have an extra 'NULL' attribute that I can't seem to get rid of, but I am unsure if that is the root of the problem.
In short, how do I extract the plain numbers from that matrix? Or is there a better way to do this in shiny? The only other solution I'm aware of is the rhandsontable package, which I would prefer not to use if there is a reasonable alternative.
Any suggestions would be very appreciated. Thank you!
Edit/solution: replacing renderUI and uiOutput with renderPrint and verbatimTextOutput solves the problem. Thank you for the comment, blondeclover!