Icons in data table in Shiny - r

I am trying to add a column of icons to a data table that is shown in a Shiny app. Essentially I just want an up arrow when the data has gone up, and a down arrow when it has gone down. However, I'm not sure how to display an icon. When I add a column just using for e.g. icon("arrow-up"), I get the following error:
Error: default method not implemented for type 'list'
I can see that if I try this approach outside of Shiny, it is displaying the data about the icon rather than displaying the icon.
One option might be to use the approach of adding it as an image - but it feels like there would be a more direct way? I'm also not sure how to do that with Font Awesome icons.
Apologies if this is basic - I couldn't find an answer!
Here is a simplified version of what I'm doing:
library(shiny)
library(shinydashboard)
number_compare <- data.frame(replicate(2, sample(1:100, 10, rep=TRUE)))
number_compare$direction <- ifelse(number_compare$X1 < number_compare$X2, "Up", "Down")
number_compare$direction <- ifelse(number_compare$X1 == number_compare$X2, "", number_compare$direction)
sidebar <- dashboardSidebar()
body <- dashboardBody(
fluidRow(box(width = 12, solidHeader = TRUE,
tableOutput("example_table"))
)
)
ui <- dashboardPage(dashboardHeader(title = "Example"),
sidebar,
body
)
server <- function(input, output) {
output$example_table <- renderTable(number_compare)
}
shinyApp(ui, server)

You don't say what icons you want to use, so I will assume angle-up and angle-down from fontawesome, but you can also use glyphicons.
As you point out, the output of icon() is a list. Assigning that in your ifelse would give a column repeating the values i, iconname, and NULL.
Instead, try wrapping icon() in as.character() to give the raw HTML for the icon. E.g:
number_compare$direction <- ifelse(
number_compare$X1 < number_compare$X2,
as.character(icon("angle-up")),
as.character(icon("angle-down"))
)
This will fill the column with values like <i class="fa fa-angle-up"></i> which you can print in the app as raw HTML.
Alternatively, you can use HTML escape codes to print the arrows without using icons. See https://www.w3schools.com/charsets/ref_utf_arrows.asp for a list of HTML escape codes.
Edit: Whenever you include raw HTML in a table, make sure that shiny doesn't escape it. Replace your call to renderTable(number_compare) with renderTable(number_compare, sanitize.text.function = function(x) x)
(based on r shiny table not rendering html)

Related

rpivotTable: remove unnecessary aggregators

I create a interactive pivot table by using rpivotTable package. However, I found that some of aggregators and renderName are unnecessary for my users. I would like to remove them. For example, I want to remove "Average" from aggregator dropdown menu.
Here is my example:
library(shiny)
library(rpivotTable)
df <- iris
ui <- fluidPage(
fluidRow(
column(width=10, rpivotTableOutput("pivot"))
)
)
server <- function(input, output, session) {
output$pivot<-renderRpivotTable({
rpivotTable(df,
rendererName="Heatmap",
cols=c("Species"),
rows=c("Petal.Width"),
aggregatorName="Count",
hiddenFromAggregators=["Average"]
)
})
}
shinyApp(ui = ui, server = server)
I noticed that there seems some relevant parameters called "hiddenFromAggregators" but I cannot figure out how to apply it in R/Shiny environment.
Here is where I found "hiddenFromAggregators".
https://github.com/nicolaskruchten/pivottable/wiki/Parameters
You may be looking for something like this :
rpivotTable(iris,
rendererName = "Treemap",
cols = c("Species"),
rows = c("Petal.Width"),
aggregatorName = "Count",
aggregators = list(Sum = htmlwidgets::JS('$.pivotUtilities.aggregators["Sum"]'),
Count = htmlwidgets::JS('$.pivotUtilities.aggregators["Count"]')),
subtotals = TRUE)
There is probably a faster way than adding aggregators one by one (using full pivotUtilities.aggregators)
I couldn't find a full list of the default aggregators but you can get it with web inspector on your app (with Google Chrome: right click > inspect) and typing $.pivotUtilities.aggregators in the console tab.
The hiddenFromAggregators parameter affects which dataset attributes are eligible to be used as arguments to aggregators, rather than which aggregators are available. It is rather challenging in rpivotTable to pass in a custom set of aggregators but might be possible using something similar to the approach here: https://github.com/smartinsightsfromdata/rpivotTable/issues/81
You will need to familiarize yourself with the documentation here first: https://github.com/nicolaskruchten/pivottable/wiki/Aggregators

Shiny App - passing the string to variable

I am trying to build Shiny App that does sentiment analysis. I have the code that works fine when i execute the script normally where Rstudio is importing the data from email.csv file. This file contains only 2 columns ( SentTo and RawText) and the text i am analyzing is located in B2 cell.
Once i run the code below i get nice chart that measure the sentiment.
library(readr)
library("ggplot2")
library('syuzhet')
Emails <- read_csv("C:/email.csv")
d<-get_nrc_sentiment(Emails$RawText)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")
Now what i am trying to do is to modify this code a bit and build the Shiny application by doing next:
ui.R
# Adding the Imput text field to the app
shinyUI(fluidPage(
textAreaInput("UserInput", "Caption", "Please Enter Your Text", width =
"500px", height = "300px"),
mainPanel(
plotOutput("distPlot"))
))
Server.R
library(shiny)
library(syuzhet)
library(ggplot2)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
Emails <- input$UserInput
d<-get_nrc_sentiment(Emails)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")
})
})
After i run the app i get this error:
So ti builds the app but even when i paste some text in to the field it seems that the code i am using in server.R part is not doing what it needs to do.
If i replace the line in server.R part (Emails <- input$UserInput) with (Emails <- read_csv("C:/email.csv"))
than it works fine. This tells me that the issue is within the way i am passing the text to the Emails. Through the input form its text through the csv file it is a second row and second column that contains the data. The code that follows i think its looking that specific format.
Anybody has suggestion on how to modify this to make it work?
Thank you in advance.
I believe the issue is in line:
td_new <- data.frame(rowSums(td[1:14]))
If I change it to the following, it works for me:
td_new <- data.frame(rowSums(td))
I'm not sure why you had the 1:14 index in there, but I don't see what it does.
Before plotting in shiny, first have it output the user input so that you understand what is being passed to the next step. verbatimTextOutput('input$UserInput') and verbatimTextOutput('dput(input$UserInput)'). I'm guessing this will be a character vector of length 1.
Now, go back to your code outside of shiny and pass it this same input, formatted exactly the same. Right now your code that works is getting a data.frame from a csv file and passed a column, which would be a character vector.
Once you get it working outside of shiny, using the input as parsed by shiny, the fixes to make your shiny app work should be clear.

R: Make part of cell bold in shiny table output

I am using the R shiny app and creating a table using renderTable and tableOutput. Is it possible to make one part of a cells contents bold whilst keeping the rest of it normal text.
E.g. one entry in a particular cell could be:
5.3% ~ 1% ~ 7
I tried hardcoding ** around the appropriate figure but it just outputted the asterisk.
Thanks
You can use the <strong></strong> HTML tag in your table if you want some bold text, here's an example:
library(shiny)
data<-data.frame(a=c("<strong>a</strong>","b"),val=c(1,2))
runApp(list(
ui = basicPage(
tableOutput('mytable')
),
server = function(input, output) {
output$mytable = renderTable({
data
},sanitize.text.function=function(x){x})
}
))
You need to change the sanitize.text.function to identity in order for the tags to be interpreted.
As an alternative, you can also use Datatables to render your table. You can also use the <strong> tag, but make sure you set the escape option to false in the renderDataTable part.

R shiny data table content with html tags

I have a data table in which column a is a character field. I need to make some strings withing the column to appear with different color(just the beginning, I need to search and replace multiple strings with different colors ultimately). I'm attempting to do it the following way but unsuccessful.
Below I'm attempting to put html tags within the column values, but I'm not sure how to make the browser treat those as html tags while displaying the data table. Any ideas?
library(shiny)
library(DT)
x<-data.table(a=c("srinivas asfsis asdfsadf","vassri asdf asdfasdf","csdasdsriasfasf"))
x$a<-as.data.table(sapply(x$a,function(x)gsub("sri",'<strong style="color:red">sri</strong>',x)))
shinyApp( ui = dataTableOutput("table1"),
server = function(input, output) {
output$table1<-renderDataTable({ datatable(x) })
}
)
Please read the documentation ?DT::datatable (or the DT website). The escape argument is what you want.
datatable(x, escape = FALSE)
You've got conflicting packages that each have functions with the same name. It doesn't appear that you need anything more than the shiny package for this...
library(shiny)
x<-data.frame(a=c("srinivas asfsis asdfsadf","vassri asdf asdfasdf","csdasdsriasfasf"))
x$a<-gsub("sri",'<strong style="color:red">sri</strong>',x$a)
shinyApp( ui = fluidPage(shiny::dataTableOutput("table1")),
server = function(input, output) {
output$table1<-shiny::renderDataTable(x, escape=FALSE)
}
)

R Shiny, Remove Within-Column Filters from DataTables

[also posted in Shiny Google Group]
I am encountering some (I believe) unexpected behavior when I attempt to display a dataTable. When I display the table, my goal is to remove the majority of the sort/pagination/filter/processing options. So far setting bSort=0, bProcessing=0, bPaginate=0, bInfo=0 appears to produce desired results. However when I set bFilter=0, only the "global" filter box in the upper right had corner is removed; the within-column filter boxes remain (I expected bFilter=0 to remove all filter boxes).
Can anyone help with code to remove the within-column filter boxes (please and thank-you). [Also, I am aware of the column-specific format options, but have so-far been unable to implement them successfully to eliminate the within-column formats]. I have included minimal code below to reproduce the problem:
shinyUI(pageWithSidebar(
#my code has a header panel;
headerPanel("Table Example"),
#my code has a sidebar panel;
sidebarPanel(helpText("Stuff Here")),
#table is displayed in the main panel;
mainPanel(dataTableOutput("myTable"))
))
shinyServer(function(input, output) {
#example dataTable that produces undesired result;
output$myTable <- renderDataTable({
as.data.frame(matrix(sample(1:10,100,replace=TRUE),nrow=20,ncol=10))
}, options = list(bFilter=0, bSort=0, bProcessing=0, bPaginate=0, bInfo=0))
})
[Behavior appears both running from server and locally. Shiny 0.7.0.99. Using Google Chrome]
Thanks-in-advance!
The solution was to simply edit the css associated with the myTable output object:
I.e. change:
mainPanel(dataTableOutput("myTable"))
to
mainPanel(
dataTableOutput("myTable"),
tags$style(type="text/css", '#myTable tfoot {display:none;}')
)

Resources