How to render a special character using HTML in Shiny R? - html

I am trying to display a greek letter delta as a symbol.
The unicode and encoding can be found here.
output$text <- renderText({
HTML("Displaying greek letter delta as a symbol: \u0394")
})
This results in exactly the same string when rendered instead of a symbol. Same happens when using "Δ" or "Δ". Maybe someone knows how to correctly format text with special symbols when using HTML() in R, or share any documentation relating this?
The desired output is: "Displaying greek letter delta as a symbol: Δ"
Here is a minimal example:
library(shiny)
ui <- fluidPage(
textOutput("text")
)
server <- function(input, output, session) {
output$text <- renderText({
HTML("Displaying greek letter delta as a symbol: \u0394")
})
}
shinyApp(ui, server)

Important: if you need to use HTML elements such as <br>, you will need to follow #Stéphane Laurent's comment and use renderUi() and uiOutput().
library(shiny)
ui <- fluidPage(
uiOutput("text")
)
server <- function(input, output, session) {
output$text <- renderUI({
HTML("<p> Displaying greek letter delta as a symbol:<br> \u0394
</p>")
})
}
shinyApp(ui, server)
Created on 2022-06-01 by the reprex package (v2.0.1)
With:
R version 4.2.0 (2022-04-22 ucrt)
shiny_1.7.1
Running under: Windows 10 x64 (build 19044)

Related

How to use HTML tags on other tags in Shiny?

I am trying to print a title like :
There is 45% available
With 45% in bold like that, and I produced this code :
h4(paste0("There is ", strong(as.character(prctnage)), strong("%"), " available"))
Here is the output :
There is <strong>45<strong><strong>%<strong> available
Any suggestion?
See ?h4: ... arguments expect:
Tag attributes (named arguments) and children (unnamed arguments)
In your example paste0 in h4 converts the tags to a string.
library(shiny)
library(htmltools)
percentage <- 10
ui <- fluidPage(
h4("There is ", strong(paste0(percentage, "%")), " available"),
# another option:
h4(HTML(paste0("There is ", strong(as.character(percentage)), strong("%"), " available")))
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
Another option would be to mark the characters as HTML again using HTML()

Using renderUI in Shiny to display vectors

I want to be able to display a dynamic vector as text output in my Shiny app. I also want to utilize HTML (bold, font colors, etc.), so I am using htmlOutput and renderUI instead of textOutputand renderText per this suggestion.
Here is some example code:
library(shiny)
shinyApp(
ui <- htmlOutput("example"),
server <- function(input, output, session){
# vector (in the real app, this is not a static vector--it will be updated with other inputs)
states <- c("Alabama", "Alaska", "Arizona", "Arkansas")
# text output
output$example <- renderUI({
x <- paste0("<strong>Here are your states</strong>: ", states)
HTML(x)
}) #END RENDERUI
} #END SERVER
) #END SHINYAPP
The result of this code is:
Here are your states: Alabama Here are your states: Alaska Here are
your states: Arizona Here are your states: Arkansas
What I want is :
Here are your states: Alabama Alaska Arizona Arkansas
I have come up with a solution using conditional statements, but it's pretty clunky. Here's what I put in renderUI for the above desired output:
x <- paste0("<strong>Here are your states: </strong>",
if(!is.na(states[1])){states[1]},
if(!is.na(states[2])){states[2]},
if(!is.na(states[3])){states[3]},
if(!is.na(states[4])){states[4]})
HTML(x)
Again, the above solution works, but it's rather clunky and will be terribly inefficient for larger vectors (with, let's say, 10+ elements). Is there an easier way to display these vectors while still being able to utilize HTML?
You are looking for paste(..., collapse = " ").
library(shiny)
shinyApp(
ui <- htmlOutput("example"),
server <- function(input, output, session){
# vector (in the real app, this is not a static vector--it will be updated with other inputs)
states <- c("Alabama", "Alaska", "Arizona", "Arkansas")
# text output
output$example <- renderUI({
x <- paste0("<strong>Here are your states</strong>: ", paste(states, collapse = " "))
HTML(x)
}) #END RENDERUI
} #END SERVER
) #END SHINYAPP

R HTML clean up - how to get rid of strange characters in output?

I'm using R to clean up html files stored in my hard drive and then export as txt files. However, in the output text files I see a lot of strange characters such as < U+0093>,< U+0094> < U+0093> etc. It seems to me either quote mark or bullet point (or maybe some others) is not parsed/displayed correctly. How do I fix this issue?
Here is the original HTML file
Below is the code I've been using:
library(bitops)
library(RCurl)
library(XML)
rawHTML <- paste(readLines("2488-R20130221-C20121229-F22-0-1.htm"), collapse="\n")
doc = htmlParse(rawHTML, asText=TRUE, encoding="UTF-8")
plain.text <- xpathSApply(doc, "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", xmlValue)
write.table(plain.text, file="2488.txt", row.names=FALSE, col.names=FALSE, quote=FALSE)
If you just need the text, you an do a conversion to ASCII with iconv. Also, you don't need to use write.table for this as writeLines will do nicely:
library(bitops)
library(RCurl)
library(XML)
rawHTML <- paste(readLines("~/Dropbox/2488-R20130221-C20121229-F22-0-1.htm"), collapse="\n")
doc <- htmlParse(rawHTML, asText=TRUE, encoding="UTF-8")
plain.text <- xpathSApply(doc, "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", xmlValue)
writeLines(iconv(plain.text, to="ASCII"), "~/Dropbox/2488wl.txt")
You could also use rvest (you still need iconv):
library(xml2)
library(rvest)
pg <- html("~/Dropbox/2488-R20130221-C20121229-F22-0-1.htm")
target <- "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]"
pg %>%
html_nodes(xpath=target) %>%
html_text() %>%
iconv(to="ASCII") %>%
writeLines("~/Dropbox/2488rv.txt")
You can also avoid pipes if you want to:
converted <- iconv(html_text(html_nodes(pg, xpath=target)), to="ASCII")
writeLines(converted, "~/Dropbox/2488rv.txt")

CSV quick plot error

I would like to use the CSV quick plot application to analyze data however even with all the packages installed the app continues to show an error. The error message is:
Error in file(file, "rt") : cannot open the connection
Warning in run(timeoutMs) :
cannot open file
The code is below:
UI
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("CSV Quick Plot"),
sidebarPanel(
fileInput('infile', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
),
selectInput("plotType", label = "Select Plot Type",
c("Histogram" = "hist",
"Correlation" = "corr")),
dateInput("date", "Date:"),
submitButton("Submit")
),
mainPanel(
h3('Output Information'),
h4('File entered'),
verbatimTextOutput("ofile"),
h4('You selected plot type'),
verbatimTextOutput("oplotType"),
h4('You entered'),
verbatimTextOutput("odate"),
plotOutput('newHist')
)
))
server
library(UsingR)
library(shiny)
library(Hmisc)
library(corrplot)
wd <- getwd()
setwd(wd)
shinyServer(
function(input, output) {
output$ofile <- renderPrint({input$infile})
output$oplotType <- renderPrint({input$plotType})
output$odate <- renderPrint({input$date})
plotdata <- reactive({
filestr <- input$infile
read.csv(filestr$name)
if(is.null(input$file1))
return(NULL)
})
output$newHist <- renderPlot({
hist(plotdata())
})
# Conditional plot selection is test in progress
# corrdf <- cor(plotdata)
# output$newHist <- renderPlot({
# corrplot(corrdf, method = "circle")
# })
}
)
Please help me in getting this application to run. Thank you!
There are three problems with your code.
you're checking for if(is.null(input$file1)) but I believe you want to use input$infile
the above check should be done BEFORE read.csv because if there is no file chosen, you don't want to read a file
when reading the file you want to use filestr$datapath instead of filestr$name. The name only gives you the name of the file on the user's local machine, while the datapath gives the actual full path to the file that's been uplodaed
Here is a simplification of your app that only deals with selecting a file and reading it into csv, demonstrating all those points
runApp(shinyApp(
ui = fluidPage(
fileInput('infile', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
)
),
server = function(input, output, session) {
plotdata <- reactive({
if (is.null(input$infile)) {
return()
}
filestr <- input$infile
read.csv(filestr$datapath)
})
observe({
cat(str(plotdata()))
})
}
))

Hide renderPrint Pre Tag Output from Shiny Application in R

I am developing a Shiny application in R. For certain pieces of renderPrint output I would like the shiny user interface to display nothing. Kind of like the hidden option for pre or div tags in HTML5 example shown below:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_hidden
Below is my shiny example code. A brief explanation: you can use a drop down menu to select one of two variables (factor variable or continuous variable). If you select the factor variable I want to show the caption and the table output. If you select the continuous variable I don't want to see anything. Right now, the caption disappears if you insert a blank string "" as the return to renderText. However, I don't know how to get renderPrint to show nothing. I've tried:
"". Doesn't work as it returns the actual blank string
NULL. Doesn't work as it returns the string NULL
invisible(). Best so far, but still doesn't work as it returns the grey formatted box.
Goal is to just display nothing. Shiny ui.r and server.r code given below:
library(shiny)
##
## Start shiny UI here
##
shinyUI(pageWithSidebar(
headerPanel("Shiny Example"),
sidebarPanel(
wellPanel(
selectInput( inputId = "variable1",label = "Select First Variable:",
choices = c("Binary Variable 1" = "binary1",
"Continuous Variable 1" = "cont1"),
selected = "Binary Variable 1"
)
)
),
mainPanel(
h5(textOutput("caption2")),
verbatimTextOutput("out2")
)
))
##
## Start shiny server file and simulated data here
##
binary1 <- rbinom(100,1,0.5)
cont1 <- rnorm(100)
dat <- as.data.frame(cbind(binary1, cont1))
dat$binary1 <- as.factor(dat$binary1)
dat$cont1 <- as.numeric(dat$cont1)
library(shiny)
shinyServer(function(input, output) {
inputVar1 <- reactive({
parse(text=sub(" ","",paste("dat$", input$variable1)))
})
output$caption2 <- renderText({
if ( (is.factor(eval(inputVar1()))==TRUE) ) {
caption2 <- "Univariate Table"
} else {
if ( (is.numeric(eval(inputVar1()))==TRUE) ) {
caption2 <- ""
}
}
})
output$out2 <- renderPrint({
if ( (is.factor(eval(inputVar1()))==TRUE) ) {
table(eval(inputVar1()))
} else {
if ( (is.numeric(eval(inputVar1()))==TRUE) ) {
invisible()
}
}
})
})
A few questions...
Why does renderText handle hidden/invisible presentation different than renderPrint? Is it because the former outputs text as pre tag; whereas, the latter displays formatted output in div tag?
To those HTML experts (upfront, I am not one)...what option would be best to get my output to display nothing? Is the hidden option embedded in a pre or div tag best (I know it doesn't work in IE browsers). Should I try something else? CSS options, etc?
Assuming hidden is the best way to go (or that I get an answer to 2. above), how do I pass this option/argument through the renderPrint function in shiny? Or would I need to use a different shiny function to achieve this functionality?
Btw...My R version is: version.string R version 3.0.1 (2013-05-16) and I am using shiny version {R package version 0.6.0}. Thanks in advance for your help.
I am not sure that I have understood your question, but try the following:
here is the Ui first:
library(shiny)
ui <- fluidPage(pageWithSidebar(
headerPanel("Shiny Example"),
sidebarPanel(
wellPanel(
selectInput(inputId = "variable1",label = "Select First Variable:",
choices = c("Binary Variable 1" = "binary1",
"Continuous Variable 1" = "cont1"),
selected = "Binary Variable 1"
)
)
),
mainPanel(
h5(textOutput("caption2")),
verbatimTextOutput("out2", placeholder=TRUE)
)
))
Start shiny Server file and simulated data here:
binary1 <- rbinom(100,1,0.5)
cont1 <- rnorm(100)
dat <- as.data.frame(cbind(binary1, cont1))
dat$binary1 <- as.factor(dat$binary1)
dat$cont1 <- as.numeric(dat$cont1)
server <- (function(input, output) {
inputVar1 <- reactive({
parse(text=sub(" ","",paste("dat$", input$variable1)))
})
output$caption2 <- renderText({
if ((is.factor(eval(inputVar1()))==TRUE) ) {
caption2 <- "Univariate Table"
} else {
if ((is.numeric(eval(inputVar1()))==TRUE) ) {
caption2 <- "Continous"
}
}
})
output$out2 <- renderPrint({
if ((is.factor(eval(inputVar1()))==TRUE) ) {table(eval(inputVar1()))}
})
})
And finally:
shinyApp(ui = ui, server = server)