using user interface, nearpoint/renderprint/verbatimTextOutput('print') to show part of variables on user click - html

Below I attach the code I use for the Shiny application. I am wondering how I can specifically use click="plot_click"/near-point/render print, to show part of data(). If you look at the attached image, you see that bunch of info has appeared see image, but I need to take "name", and winning times only.
#code------------------------------------
server<- function(input, output, session) {
#wrangling data:
gslam<- as.data.frame(gslam1)
gslam$tournament <- sapply(gslam$tournament, function(val)
{agrep(val, c('Australian Open', 'U.S.
Open','Wimbledon','FrenchOpen'),
value = TRUE)})
#pivot plot based on Tournament
reactive_data<-reactive({
req(input$sel_tournament)
df<- gslam %>% filter(tournament %in%
input$sel_tournament)%>%group_by(winner,tournament)%>%
mutate(winningNumber=n())
df<-df %>% arrange(winner)
})
#dynamic list
observe({
updateSelectInput(session,"sel_tournament", choices =
gslam$tournament, select="U.S. Open")
})
# create the plot
output$WinnerPlot <- renderPlot({
g<- ggplot(reactive_data(),aes( y =winner, x
=winningNumber),decreasing=FALSE) +
theme(legend.position=none")
g+geom_bar(stat="identity",width=0.5, fill="black")})
output$print = renderPrint({
nearPoints(
reactive_data(), # the plotting data
input$plot_click, # input variable to get the x/y
maxpoints = 1, # only show the single nearest point
threshold = 1000 # basically a search radius. set this big
# to show at least one point per click
)})
output$Top5Plot <-renderPlot({
g<- ggplot(reactive_data(),aes( y =winner, x
=winningNumber),decreasing=FALSE) + theme(legend.position =
"none")
g+geom_bar(stat="identity",width=0.5, fill="black")
})
}
ui <- navbarPage("Grand Slam Shiny Application", id="cc",
tabPanel("Winners' Rank",
fluidRow(titlePanel("Grand Slam
ShinyApp"),
sidebarPanel(
selectInput(inputId =
"sel_tournament",label="Choose Tournament:","Names"))),
plotOutput(("WinnerPlot"), click="plot_click"),
verbatimTextOutput('print')
),
tabPanel("Top 5 Winners' Performance",
plotOutput("Top5Plot"))
)
# Run the App
shinyApp(ui, server)

You may take help of dplyr::select in nearPoints.
output$print = renderPrint({
nearPoints(
dplyr::select(reactive_data(), winner, winningNumber),
input$plot_click,
maxpoints = 1,
threshold = 1000
)})

Related

How define Server for Copy/Paste regions as input in R/Shiny?

I have a shiny which can be used to overlap between query regions and a given data table (e.g. DF). I put two options for uploading query data 1) as .bed format and 2) inserting data as copy/paste.
The shiny works well with uploading .bed file but I am not sure how can I define Server for copy/paste (text) data.
Thank you in advance for any suggestion!
DF<- data.table(chr=c("chr1","chr2"),start=c(10,20),end=c(20,30))%>% setkey(chr, start, end)
text<- data.table(chr=c("chr1","chr2"),start=c(15,25),end=c(15,30))%>% setkey(chr, start, end)
ui <- fluidPage(
sidebarLayout(
sidebarPanel (
p(strong ("Find overlap between query file and data"),style = "color:blue;"),
br(),
selectInput("choose","Choose file source",choices = c("file","text"),selected = "file"),
conditionalPanel("input.choose=='file'",
fileInput("query.file", "Upload genomic coordinates in .bed
format:",multiple = F,accept = ".bed")),
conditionalPanel("input.choose=='text'",
textAreaInput("query.text", "Enter genomic coordinates:")),
actionButton("run", "run"),
width = "2"),
mainPanel(
dataTableOutput("DFtable"),
dataTableOutput("overlap_table"))
)
)
server <- function (input, output, session) {
## Read user .bed file
user_query.file <- reactive({
req(input$query.file)
ext <- tools::file_ext(input$query.file$name)
switch(ext,
bed = fread(input$query.file$datapath,header=F)%>%
dplyr::rename (chr =V1, start=V2, end=V3) %>% setkey(chr, start, end)%>% unique()
)
})
## overlapping between query file and table
overlap <- eventReactive(input$run, {
req(input$run)
withProgress(message = 'Analysis in progress', value = 0, {
query.overlap<- foverlaps(user_query.file() ,DF, nomatch = 0) %>%
unique()
})
})
## output
output$DFtable<- renderDataTable({ DF })
output$overlap_table <- renderDT({overlap () })
}
shinyApp(ui, server)
Desire out put using TEXT input option:
chr start end i.start i.end
chr1 15 15 10 20
chr2 25 30 20 30
Not sure on how your copied text looks like, but assuming something like:
chr,start,end
chr1,10,20
chr4,34,56
All you need is to parse the text contents of the UI input and assigned it to DF variable. Your run event handler could look like:
## overlapping between query file and table
overlap <- eventReactive(input$run, {
req(input$run)
#Requiring text input and parsing it
req(input$query.text)
DF <- data.table(read.csv(text=input$query.text)) %>% setkey(chr, start, end)
withProgress(message = 'Analysis in progress', value = 0, {
query.overlap<- foverlaps(text ,DF, nomatch = 0) %>%
unique()
})
})
Then when clicking on the run button, the analysis is executed and the overlap reactive value is updated. If the comparison is always between file and text provided, you should also include a req(user_query.file()) to ensure the file has been provided and correctly parsed.

Post local image into a popup using leaflet and R

I've been trying like crazy to add local images (as in image files in my computer) into my leaflet map using R. I have plotted around 500 coordinates analyzing some images and I wish to show that specific image when clicking (popup).
leaflet(pics) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~GPSLongitude, lat =~GPSLatitude,
color = ~pal(Married),
popup = ~SourceFile, # WISH TO ADD EMBEDDED LOCAL IMAGE IN HERE
label = mapply(function(x, y) {
HTML(sprintf("<em>%s</em></br> %s", htmlEscape(x), htmlEscape(y)))},
pics$Address, pics$DateTimeOriginal, SIMPLIFY = F),
labelOptions = lapply(1:nrow(pics), function(x) {
labelOptions(direction='auto')
}))
I am attaching 2 screenshots: one hovering the mouse and the other one clicking on a specific place. Ideally, I'd wish to show the image and the image file name when I click on each one. Is that possible?
I can also show you an RPub with the example: http://rpubs.com/laresbernardo/photomap
Hope you can help me. Thanks!
_________________________ UPDATE _________________________
All code used for this example. Basically I scan for all images with geotags, bring the address to add on a label and then plot all coordinates. When I click on a coordinate I wish to see that picture.
wd <- "/Users/bernardo/Dropbox (Personal)/Documentos/R/R Mapping/GPS Photos"
# ------------------------------------------- get the pics with geotags
library(exifr)
library(dplyr)
library(lubridate)
library(beepr)
library(maps)
time <- Sys.time(); print(time)
setwd("/Users/bernardo/Dropbox (Personal)/Imágenes")
files <- list.files(pattern = "*.jpg|*.JPG|*.png|*.PNG", recursive=T)
exif <- read_exif(files, tags = c("SourceFile", "DateTimeOriginal", "GPSLongitude", "GPSLatitude"))
pics <- exif %>% filter(!is.na(GPSLongitude)) %>%
mutate(DateTimeOriginal = ymd_hms(DateTimeOriginal))
pics$Owner <- ifelse(grepl("iPhone Maru", pics$SourceFile), "Maru", "Ber")
pics$Married <- ifelse(as.Date(pics$DateTimeOriginal) >= '2016-04-30', TRUE, FALSE)
pics$Country <- maps::map.where(database="world", pics$GPSLongitude, pics$GPSLatitude)
#lares::freqs(pics %>% filter(!is.na(Country)), Country)
# Save pics with geotags
setwd(wd)
write.csv(pics, "with_geotags.csv", row.names = F)
print(Sys.time() - time)
beepr::beep()
# ------------------------------------------- get the addresses from files
# GET ALL ADDRESSES
library(ggmap)
options(warn=-1)
setwd(wd)
pics <- read.csv("with_geotags.csv")
addresses <- read.csv("with_address.csv")
pics_to_search <- pics %>% filter(!SourceFile %in% addresses$SourceFile)
print(paste0("Without address: ",round(100 * nrow(pics_to_search)/nrow(pics), 2),"% | ", nrow(pics_to_search)))
out <- data.frame()
for (i in 1:nrow(pics_to_search)) {
Address <- revgeocode(cbind(pics_to_search$GPSLongitude, pics_to_search$GPSLatitude)[i,], output="address")[1]
if (!is.na(Address)) {
out <- rbind(out, cbind(SourceFile=as.character(pics_to_search$SourceFile[i]), Address))
print(paste(i, Address, sep=" - "))
}
}
# Save pics with geotags
pics_with_address <- rbind(out, addresses)
write.csv(pics_with_address, "with_address.csv", row.names = F)
# ------------------------------------------- Map all coordinates with leaflet
setwd(wd)
library(leaflet)
library(htmltools)
library(mapview)
pics <- read.csv("with_geotags.csv")
address <- read.csv("with_address.csv")
pal <- colorFactor(c("green4", "navy"), domain = c(FALSE, TRUE))
pics <- left_join(pics, address, by=c("SourceFile"))
pics$Content <- paste("Dirección:","<em>", pics$Address,"</em>", "<br/> Fecha:", as.Date(pics$DateTimeOriginal))
leaflet(pics) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~GPSLongitude, lat =~GPSLatitude,
color = ~pal(Married),
popup = popupImage(as.character(pics$SourceFile), src = "local"),
label = mapply(function(x, y) {
HTML(sprintf("<em>%s</em></br> %s", htmlEscape(x), htmlEscape(y)))},
pics$Address, pics$DateTimeOriginal, SIMPLIFY = F),
labelOptions = lapply(1:nrow(pics), function(x) {
labelOptions(direction='auto')
}))
But...
I even installed the latest version with devtools::install_github("r-spatial/mapview#develop")
With no reproducible example it is hard, but takes this for instance:
library(leaflet)
library(mapview)
# make-up dataset
data_df <- data.frame(lat = as.numeric(c("35.68705", "35.88705")), long = as.numeric(c("51.38", "53.35")))
# Loaded random pictures on my laptop
images <- c("/PathToImage1/download.jpeg",
"/PathToImage2/download1.jpeg")
leaflet(data_df) %>%
addTiles() %>%
addCircleMarkers(
fillOpacity = 0.8, radius = 5,
lng = ~long, lat =~lat,
popup = popupImage(images)
)
Click on each point to see a different image. Make sure to load your images in the same order as your data frame.
Finally after lots of hours wasted in this problem, I managed to fix the issue. Thanks to #MLavoie and #TimSalabim3 (via Twitter) for the support.
This was it: if you are running macOS, you should have installed a driver called gdal. I literally just installed it, ran the original script and it worked. Don't know what that gdal does but it really did the job!

Shiny isolate - How not to send the hidden conditional input data to the server?

How can I ask Shiny not to send the hidden conditional input data to the server from the Shiny UI?
I have this problem which I don't know how to solve it.
When I select 'One site' and the dropdown select options for the site 2 will be hidden and I don't want any of the site 2 data to be sent to the server.
But Shiny does send the hidden input data to the server when I hit the GO button. How can I not to send it?
Below are my code,
ui.R,
# Site 1 options.
site1 <- selectInput(
inputId = "site1",
label = "Select a first site:",
choices = c('1a', '1b')
)
# Site 2 options.
site2 <- selectInput(
inputId = "site2",
label = "Select a second site:",
choices = c('2a', '2b')
)
shinyUI(
pageWithSidebar(
headerPanel("Shiny App"),
sidebarPanel(
selectInput(
"distribution",
"Please select a type:",
choices = c("Both sites", "One site")
),
# Site select input.
site1,
# Condition when the plot is a line plot.
conditionalPanel(
condition = "input.distribution == 'Both sites'",
site2
),
actionButton("goButton", "Go!")
),
mainPanel(
plotOutput("myPlot")
)
)
)
server.R,
shinyServer(
function(input, output, session) {
output$myPlot = renderPlot({
# Take a dependency on input$goButton
input$goButton
site1 <- isolate(input$site1)
site2 <- isolate(input$site2)
plot(1, 1, col = "white")
text(1, 1, paste(site1, " ", site2))
})
}
)
Here are the visual:
two sites (correct result),
one site (incorrect result),
the expected result,
Any ideas? Is it a bug from Shiny?

selectInput in R shiny

I want to select from a list read in from a Mysql query. I am getting an error in the code. I must be doing something just completely wrong, but not sure what.
I would like to select from a list of skus read in from a sql query. I get an error in the ui portion.
I am not even sure if this is possible, but to list out all skus would be extremely timely.
I am getting the following errors:
Error in tag("div", list(...)) :
argument "sidebarPanel" is missing, with no default
shinyApp(ui = ui, server = server)
Error in force(ui) : object 'ui' not found
library('RMySQL')
library('plyr')
library('shiny')
library('scales')
library(shinyapps)
library(ggplot2)
con <- dbConnect(MySQL(), user="user", password="password",dbname="DB", host="host");
rank<-dbGetQuery(con,"select sku from DB")
#build a shiny app to select which sku to pick
server <- function(input, output) {
output$distPlot <- renderPlot({
hist(rnorm(input$obs), col = 'darkgray', border = 'white')
})
}
ui <- pageWithSidebar(
## Application title
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input', choices = unique(rank$sku),
selectize = FALSE
),
mainPanel(plotOutput("distPlot"))
)
)
shinyApp(ui = ui, server = server)
You have both a missing bracket near your selectize = FALSE and (as #DavidRobinson has suggested) you need a headerPanel.
CODE FIX
library(shiny)
library(ggplot2)
# con <- dbConnect(MySQL(), user="user", password="password",dbname="DB", host="host");
# rank<-dbGetQuery(con,"select sku from DB")
# for test hard coding the rank as I dont have your data
# test rank
rank$sku <- c(1,2,3)
#build a shiny app to select which sku to pick
server <- function(input, output) {
output$distPlot <- renderPlot({
hist(rnorm(input$obs), col = 'darkgray', border = 'white')
})
}
ui <- pageWithSidebar(
## Application title
# missing headerPanel
headerPanel(title = "Hello"),
# missing bracket after selectize
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input', choices = unique(rank$sku),
selectize = FALSE)
),
mainPanel(plotOutput("distPlot"))
)
shinyApp(ui = ui, server = server)
RESULT
ANOTHER SHINY PAGE UI OPTION
You can can also use a tabbed page structure, replacing ui above with this code (note it does not require headerPanel like above):
# navbar tabbed page example - without headerPanel
ui2 <- navbarPage(title = "Hello Another Style",
tabPanel("Chart Panel",
sidebarLayout(
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input',
choices = unique(rank$sku),
selectize = FALSE)
),
mainPanel(
plotOutput("distPlot")
)
)
),
tabPanel("Instructions",
mainPanel(
p("Notes here for example...")
)
)
)
SECOND RESULT
And then on second panel...
DEBUGGING ADVICE
These Shiny pages can have lots of brackets, so pace over your code selecting brackets in turn carefully in your editor like RStudio to make sure your brackets match okay.
All the best!

how dynamically read image file shiny R

I'm downloading a png image according to user provided input, and I show the image with
mainPanel(
img(src="file.png", height =1187 , width = 748)
)
but, if the user changes the input I have to refresh the page.
The app draft is follows below
the ui
library(shiny)
org <- read.delim("http://rest.kegg.jp/list/organism", header=FALSE)
org <- apply(org[,2:3], 1, function(x) paste(as.matrix(x), collapse="-"))
# Define UI for dataset viewer application
shinyUI(fluidPage(
# Application title
titlePanel("Reactivity"),
# Sidebar with controls to provide a caption, select a dataset, and
# specify the number of observations to view. Note that changes made
# to the caption in the textInput control are updated in the output
# area immediately as you type
sidebarLayout(
sidebarPanel(
textInput("caption", "Caption:", "Data Summary"),
tags$textarea(id="foo", rows=3, cols=40, "Default value"),
selectInput("dataset", "Choose an organism:",
choices = org ),
numericInput("obs", "Number of observations to view:", 10)
),
# Show the caption, a summary of the dataset and an HTML table with
# the requested number of observations
mainPanel(
h3(textOutput("caption")),
verbatimTextOutput("summary"),
tableOutput("view"),
plotOutput('plot1'),
img(src="file.png", height =1187 , width = 748)
)
)
))
and the server
library(shiny)
# Define server logic required to summarize and view the selected dataset
shinyServer(function(input, output) {
output$caption <- renderText({
cps <- strsplit(input$foo, "\\s+")[[1]]
#tab <- read.table("http://rest.kegg.jp/link/pathway/zma")
#path2cpd <- read.table("http://rest.kegg.jp/link/pathway/compound")
#allmetab <- unique(path2cpd[which(path2cpd[,2] %in% sub("path:zma", "path:map", tab[,2])),])
#cps <- unique(allmetab[,1])
#
url <- "http://www.kegg.jp/kegg-bin/show_pathway?zma00944+default%3dred+"
url <- paste(url, paste(cps, collapse="+"), sep="+")
download.file(url, "form.html")
lines <- readLines("form.html")
imgUrl <- lines[grep('img src="/', lines)]
url <- paste0("http://www.kegg.jp/", strsplit(imgUrl, '"')[[1]][2])
download.file(url, "www/file.png")
url
})
# The output$summary depends on the datasetInput reactive expression,
# so will be re-executed whenever datasetInput is invalidated
# (i.e. whenever the input$dataset changes)
output$plot1 <- renderPlot({
})
})
if you paste the compound codes
C01477
C04608
C04858
C05622
in the box with "Default Value" written I would like to automatically update the picture, or at least have a button to update without having to reload all the app.
If one reloads the navigator one can see the figure with the red dots colored (at the page bottom).
How can I make the function read the image again after a time interval?