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

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:

Related

How can I render HTML content in an R Shiny Popify (ShinyBS) tooltip?

I'm building out a datatable in R Shiny and part of it will include tooltips unique to each cell. I've accomplished that, however, I seem to be unable to insert HTML content into the tooltip itself. In the example below, I'm inserting HTML content into a cell in the datatable, and then aim to insert that same content into a tooltip, but the HTML only renders in the datatable, and not in the tooltip.
I've played around with a few ideas but can't find any that work. I can get the HTML to appear (as text) in the tooltip by removing the HTML function, but then, obviously, it's escaped and is just text. I am able to bold text within the tooltip using tags$b(), however, I am hoping for a solution more similar to my example below as I have more complex HTML content I would like add to the tooltip beyond just text.
Any ideas? Thanks very much!
library(shiny)
library(shinyBS)
library(DT)
ui <- fluidPage(
bsTooltip('tbutton',''),
mainPanel(dataTableOutput('df'))
)
server <- function(input, output) {
df <- data.frame(A = c(1:5), B = c(LETTERS[1:5]))
output$df <- renderDataTable({
cell <- paste0('<svg width="30" height="30">',
'<text x="1%" y="75%" font-weight="bold" font-size="16" >B</text>',
'</svg>')
df[2,2] <- as.character(popify(tags$div(HTML(cell)),
title = 'Tooltip:',
placement = 'left',
content = paste0(tags$div(HTML(cell))),
trigger = c('hover', 'click')))
datatable(df, escape=FALSE)
})
}
shinyApp(ui = ui, server = server)
To attach a popover to a cell, you can use bsPopover if this cell has an id. To set an id to the cells, you can use the datatables option createdCell.
Then the HTML code works in the popover content, but not the SVG (or at least I didn't manage to make it work).
library(shiny)
library(shinyBS)
library(DT)
df <- data.frame(A = 1:5, B = LETTERS[1:5])
css <- "
.red {color: red;}
"
ui <- fluidPage(
tags$head(tags$style(HTML(css))),
mainPanel(
DTOutput('df'),
bsPopover(
id = "id2",
title = "test",
content = '<p class="red">TEST</p>'
)
)
)
server <- function(input, output) {
output$df <- renderDT({
datatable(
df,
options = list(
columnDefs = list(
list(
targets = 2,
createdCell = JS(
"function (td, cellData, rowData, row, col) {",
" $(td).attr('id', 'id' + (row+1));",
"}"
)
)
)
)
)
})
}
shinyApp(ui = ui, server = server)

How to pass a list of urls contained in a dataframe column into a leaflet map?

I want to make a map using leaflet so that the points in the map have popup notes. Each popup will have a clickable link to redirect to an Internet page. The URLs that will be inserted in such popups are in a column of my data frame, which has thousands of rows. Some toy data:
place <- c("a", "b", "c", "d", "e", "f")
thing <- c("potato","melon","black pepper", "bigfoot","black panther", "orchidaceae")
lat <- c(-17.456, 31.4009, 24.293, -8.956, 8.697, -25.257)
long <- c(-63.658,-111.144,-106.759,-81.029,-83.2052,-52.026)
urls <- c("https://en.wikipedia.org/wiki/Potato",
"https://en.wikipedia.org/wiki/Melon",
"https://en.wikipedia.org/wiki/Black_pepper",
"https://en.wikipedia.org/wiki/Bigfoot",
"https://en.wikipedia.org/wiki/Black_panther",
"https://en.wikipedia.org/wiki/Orchidaceae")
d <- data.frame(place, thing, lat, long, urls)
And this is the code I've been trying to use to plot the map:
library(leaflet)
library(tidyverse)
content <- paste("The", thing,
"occurs near.You can find some information",
"<b><a href=d$urls>here</a></b>")
mymap <- d %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups =
c("Toner Lite", "World Imagery")) %>%
addMarkers(label = thing,
popup = content,
icon = ~ icons(iconUrl = "marker_red.png",
iconWidth = 28, iconHeight = 24))%>%
addMiniMap(
toggleDisplay = TRUE,
tiles = providers$Stamen.TonerLite
) %>%
print()
The problem is that the word "here" in the popup is sort of clickable, but does not redirect me to any internet page. I don't know what to do in this situation where the URLs are contained in a column of my data frame. Besides, I have no experience working with HTML objects. Could anyone help me figure out a way to pass those URLs into the popup notes?
Thanks in advance!
The problem is with href=d$urls in the content, d$urls is assigned as the URL and the actual URL is not referred here. It can be resolved using paste0 function.
The content should be
content <- paste("The", thing,
"occurs near.You can find some information",
paste0("<b>here</b>"))
mymap <- d %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups =
c("Toner Lite", "World Imagery")) %>%
addMarkers(label = thing,
popup = content,
icon = ~ icons(iconUrl = "marker_red.png",
iconWidth = 28, iconHeight = 24))%>%
addMiniMap(
toggleDisplay = TRUE,
tiles = providers$Stamen.TonerLite
) %>%
print()

Cannot get the faded floating ui dialog box; does not show in Shiny

I am trying to fix my width on my R Shiny map. Also, I am not succeeding in making the panel faded. The width and faded panel I want to replicate is here at this link:
https://shiny.rstudio.com/gallery/superzip-example.html
I am using their style css file, this link: https://github.com/rstudio/shiny-examples/blob/master/063-superzip-example/styles.css
I have written my code:
library(shiny)
library(tidyverse)
library(leaflet.extras)
library(leaflet)
library(RColorBrewer)
library(scales)
library(lattice)
library(dplyr)
fake_data <- read.csv("https://raw.githubusercontent.com/gabrielburcea/stackoverflow_fake_data/master/gather_divided.csv")
# Define UI for application that draws a histogram
ui <- fluidPage(
navbarPage("Covid-19 Symptom Tracker", id = "nav",
tabPanel("Interactive map",
div(class = "outer",
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "style.css")
),
leafletOutput("map", width = "100%", height = "96vh"), #height = "99vh"
#Floating panel
absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE,
draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
width = 330, height = "auto",
h4("SARS-Covid-19 symptoms"),
selectInput("symptom", "Select symptom", c("Chills",
"Cough", "Diarrhoea",
"Fatigue",
"Headache",
"Loss of smell and taste",
"Muscle ache",
"Nasal congestion",
"Nausea and vomiting",
"Shortness of breath",
"Sore throat",
"Sputum",
"Temperature")
),
tags$div(id="cite",
'Data provided by Your.md'
)
)))
)
)
server <- function(input, output) {
filtered_data <- reactive({
fake_data %>%
dplyr::filter(Symptom %in% input$symptom)
})
output$map <- renderLeaflet({
leaflet() %>%
addTiles(urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png",
attribution = 'Maps by Mapbox') %>%
addMarkers(data = filtered_data(), clusterOptions = markerClusterOptions())
})
}
# Run the application
shinyApp(ui = ui, server = server)
And the css style I am using (just the same as theirs) is here:
https://github.com/gabrielburcea/stackoverflow_fake_data/blob/master/style.css
The panel I have is this which is obviously different than the one in the link I provided:
I get the following output:
when I run your code. I like the floating dialog box which fades. There is some white space along the title, and some more when I zoom out completely. It looks fine to me. Also, I saved the CSS file via Notepad. I don't think that should make any difference if you saved it via RStudio.

Extend width of column with renderDataTable in Shiny

I having trouble understanding the behavior of renderDataTable function using Shiny.
I am trying to extend the width of one specific column.
When I am not using Shiny, and just trying to visualize the output of the table, I write the below and I get the expected output in the plot (Amazon Title column is extended):
Category <- c("Tools & Home Improvement", "Tools & Home Improvement")
AmazonTitle <- c("0.15,Klein Tools NCVT-2 Non Contact Voltage Tester- Dual Range Pen Voltage Detector for Standard and Low Voltage with 3 m Drop Protection", " ABCDFGEGEEFE")
ASIN_url <- c("<a href='https://www.amazon.com/dp/B004FXJOQO'>https://www.amazon.com/dp/B004FXJOQO</a>", "<a href='https://www.amazon.com/dp/B004FXJOQO'>https://www.amazon.com/dp/B0043XJOQO</a>")
ASIN <- c("B004FXJOQO", "B0043XJOQO")
All_ASIN_Information <- data.frame(Category, AmazonTitle, ASIN_url, ASIN)
DT::datatable(All_ASIN_Information, escape=FALSE,
options = list(
pageLength = 20, autoWidth = TRUE,
columnDefs = list(list( targets = 2, width = '600px'))
)
)
But when I use this exact block inside a DT::renderDataTable function for Shiny, the result is different and the column width is not extended....
See behavior for Shiny with below code:
library(shiny)
library(DT)
ui <- fluidPage(
mainPanel(
DT::dataTableOutput("Table_ASIN")))
server <- function(input, output){
output$Table_ASIN <- DT::renderDataTable(
DT::datatable(All_ASIN_Information, escape=FALSE,
options = list(
pageLength = 20, autoWidth = TRUE,
columnDefs = list(list( targets = 2, width = '600px'))
)))
}
shinyApp(ui, server)
I don't know if this behavior is caused by the hyperlinks created in column 'ASIN_url' but I would really need them anyway.
Any help much appreciated on this !
One option would be to shorten the link like this:
ASIN_url <- c("<a href='https://www.amazon.com/dp/B004FXJOQO'>Link</a>", "<a href='https://www.amazon.com/dp/B004FXJOQO'>Link</a>")
Another would be to add a scroll bar by including scrollX = TRUE in the option list

unable to place logo / image in Shiny App

I'm trying my best to place a logo in my shiny app, but its showing blue question mark every time. I made a separate ui and server file as well but still didn't work. I also made a 'www' folder and set it as a working directly with image inside it, but no result.
Can someone please guide me?
library(dplyr)
library(shiny)
library(shinythemes)
#UI
ui = fluidPage(img(src = "picture.jpg"), fluidRow( rpivotTableOutput("pivot")))
#Server
server = function(input, output, session) {reactive({
mtcars %>% select(cyl, carb, vs, mpg) %>% group_by(carb,vs ) %>% summarise(mpg=sum(mpg))})
output$pivot <- renderRpivotTable( rpivotTable::rpivotTable(mtcars, rows = c( "vs"),cols=c("carb"), vals = "mpg", aggregatorName = "Sum", rendererName = "Table", width="50%", height="550px"))}
shinyApp(ui = ui, server = server)