using pickerInput in r shiny to apply function - r

I would like to be able to apply a function to a given set of columns from the RLdata10000 dataset. I have been going through shiny tutorials and am attempting to learn how to use observeEvent and actionButton. However, I would like to be able to pick the columns I use so I came across pickerInput. In short, I would like to be able to pick a set of columns from RLdata10000, and apply the function via actionButton.
My problem is that I get an error: Error: unused argument (RLdata10000). My code is below. I would like to be able to do this with two data files eventually. Any help would be appreciated.
library(shiny)
library(DT)
library(shinyWidgets)
library(plyr)
library(dplyr)
library(RecordLinkage)
data(RLdata10000)
cleanup <- function(x){
x <- as.character(x) # convert to character
x <- tolower(x) # make all lowercase
x <- trimws(x, "both") # trim white space
return(x)
}
ui <- basicPage(
h2("Record Linkage Data"),
actionButton(inputId = "clean", label = "Clean Data")
pickerInput(width = "75%",
inputId = "pick_col1",
label = "Select columns to display",
choices = colnames(RLdata10000),
selected = colnames(RLdata10000),
options = list(
`actions-box` = T,
`selected-text-format` = paste("count > ", length(colnames(RLdata10000)) - 1),
`count-selected-text` = "Alle",
liveSearch = T,
liveSearchPlaceholder = T
),
multiple = T)
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
observeEvent(input$clean, {
output$mytable = DT::renderDataTable({
lapply(input$pick_col1, cleanup)
})
}
}
shinyApp(ui, server)

I wasn't actually able to replicate the error you noted, but you had a few issues that were preventing you from getting what (I think) you're after.
First, you were missing commas in the UI after the actionButton and pickerInput elements.
Second, you are only giving lapply the names of columns - not the data - when you use input$pick_col1, so your cleanup function has nothing to work on. Using select from dplyr provides a simple way to name the columns and get the data too.
Last, renderDataTable wants a table format as an input (i.e., either a data frame or a matrix), but lapply produces a list. You need to convert the output of lapply into a workable class.
From these three changes, updated code would look like this:
library(shiny)
library(DT)
library(shinyWidgets)
library(plyr)
library(dplyr)
library(RecordLinkage)
data(RLdata10000)
cleanup <- function(x){
x <- as.character(x) # convert to character
x <- tolower(x) # make all lowercase
x <- trimws(x, "both") # trim white space
return(x)
}
ui <- basicPage(
h2("Record Linkage Data"),
actionButton(inputId = "clean", label = "Clean Data"),
pickerInput(width = "75%",
inputId = "pick_col1",
label = "Select columns to display",
choices = colnames(RLdata10000),
selected = colnames(RLdata10000),
options = list(
`actions-box` = T,
`selected-text-format` = paste("count > ", length(colnames(RLdata10000)) - 1),
`count-selected-text` = "Alle",
liveSearch = T,
liveSearchPlaceholder = T
),
multiple = T),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
observeEvent(input$clean, {
output$mytable = DT::renderDataTable({
data.frame(lapply(select(RLdata10000, input$pick_col1), cleanup))
})
})
}
shinyApp(ui, server)

Related

Shiny, reuss reactive input pickerInput

I am trying to create my first shiny app but I am facing a difficulty: in the reproducible example below I am creating a reactive pickerInput (i.e. only show brands proposing a cylindre equal to the input visitors select).
I then want that based on the combination input_cyl and picker_cny (remember that picker_cny depends on input_cyl) to display a table which shows the relevant data for the observation matching the combination input_cyl and picker_cny.
Thank you for your help!
df <- mtcars
df$brand <- rownames(mtcars)
df$brand <- gsub("([A-Za-z]+).*", "\\1", df$brand)
if (interactive()) {
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(shinycssloaders)
# Define UI -----------------------------------------------
ui <- fluidPage(
# Application title
titlePanel("Reproducible Example"),
# Parameters
sidebarLayout(
sidebarPanel(
selectInput(inputId = "input_cyl", label = "Cyl",
choices = c("6", "4", "8")),
pickerInput(
inputId = "picker_cny",
label = "Select Company",
choices = paste0(unique(df$brand)),
options = list(`actions-box` = TRUE),
multiple = TRUE),
width = 2),
# Show Text
mainPanel(
tableOutput("table"),
width = 10)
))
# Define Server ------------------------------------------
server <- function(input, output, session) {
# Reactive pickerInput ---------------------------------
observeEvent(input$input_cyl, {
df_mod <- df[df$cyl == paste0(input$input_cyl), ]
# Method 1
disabled_choices <- !df$cyl %in% df_mod$cyl
updatePickerInput(session = session,
inputId = "picker_cny",
choices = paste0(unique(df$brand)),
choicesOpt = list(
disabled = disabled_choices,
style = ifelse(disabled_choices,
yes = "color: rgba(119, 119, 119, 0.5);",
no = "")
))
}, ignoreInit = TRUE)
output$table <- renderTable(df)
}
}
# Run the application
shinyApp(ui = ui, server = server)
You need a reactive that will handle the change in the input and subset the dataframe before giving it to the output table. For that, you just need to add this block to your server:
data <- reactive({
if (length(input$picker_cny) > 0)
df[df$brand %in% input$picker_cny,]
else
df
})
and update the output$table like this:
output$table <- renderTable(data())
Note: feel free to remove the if else in the reactive to get that:
data <- reactive({
df[df$brand %in% input$picker_cny,]
})
The only difference in that case is: would you show all or nothing when no input has been entered yet. That's a matter of taste.

In this simple example of R using Shiny package, how would I "subset" and show a specific column of data in an output table?

I´m trying to subset a user-generated input matrix in R´s shiny and shinyMatrix packages. I´d like to extract only the values of a selected matrix column (column 3 for example) in the 2nd output table ("table2") generated by this code. The first output table ("table1") simply mimics the user inputs which works fine. I´m trying to get the second output table to show only a selected column. This will show me how to subset input data, to implement an additional function waiting in the wings.
[Side note: when running this the user may add to matrix by clicking on the bottom row of the matrix - a very nice feature! If this input feature doesn´t work well for you, it doesn´t matter for purposes of addressing this question. If you´d like it to work perfectly, then download the latest version of shinyMatrix using devtools::install_github('INWTlab/shiny-matrix'); it won´t be available on CRAN for a while.]
library(shiny)
library(shinyMatrix)
m <- diag(3)
colnames(m) <- 1:3
rownames(m) <- letters[1:3]
ui <- fluidPage(
titlePanel("Demo Matrix Input Field"),
fluidRow(
column(6, matrixInput(
inputId = "matrix",
label = "Default matrix",
value = m,
class = "numeric",
cols = list(names = TRUE,editableNames = TRUE),
rows = list(extend = TRUE,names = TRUE,editableNames = TRUE)
)
),
column(6, tableOutput("table1")),
column(6, tableOutput("table2")),
)
)
server <- function(input, output, session) {
output$table1 <- renderTable(input$matrix, rownames = TRUE)
output$table2 <- renderTable(input$matrix, rownames = TRUE)
}
shinyApp(ui, server)
Here´s what running this code looks like, I´d like that 2nd table on the bottom right to show, for example, only the column tagged 3, using subsetting:
You can use input$matrix[, 3] to show only the 3rd column in table2.
library(shiny)
library(shinyMatrix)
m <- diag(3)
colnames(m) <- 1:3
rownames(m) <- letters[1:3]
ui <- fluidPage(
titlePanel("Demo Matrix Input Field"),
fluidRow(
column(6, matrixInput(
inputId = "matrix",
label = "Default matrix",
value = m,
class = "numeric",
cols = list(names = TRUE,editableNames = TRUE),
rows = list(extend = TRUE,names = TRUE,editableNames = TRUE)
)
),
column(6, tableOutput("table1")),
column(6, tableOutput("table2")),
)
)
server <- function(input, output, session) {
output$table1 <- renderTable(input$matrix, rownames = TRUE)
output$table2 <- renderTable(input$matrix[, 3], rownames = TRUE)
}
shinyApp(ui, server)

The spaces between words in column names of a dataframe cause problem in a shiny app

I would like to display the summary and visualize the model of a regression by giving other variables as inputs every time. While the code works I changed the column names of the iris datasets by creating spaces between them and now I get error beacuse of this Error in parse: <text>:1:3: unexpected symbol
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(dplyr)
library(ggiraph)
library(ggiraphExtra)
library(plyr)
shinyApp(
ui = dashboardPagePlus(
header = dashboardHeaderPlus(title = "Social Media Metrics", titleWidth = 320
),
sidebar = dashboardSidebar(width = 320,
uiOutput("value"),
uiOutput("value2")
),
body = dashboardBody(
verbatimTextOutput("plot"),
ggiraphOutput("plot2"),
plotOutput("plot3")
)
),
server = function(input, output) {
colnames(iris)[1:4]<-c("f f","s s","d d","f f f")
output$value<-renderUI({
pickerInput(
inputId = "val"
,
label = "DEPENDENT"
,
choices = colnames(iris)[-5] #all rows of selected column
,
multiple = F, options = list(`actions-box` = TRUE)
)
})
output$value2<-renderUI({
pickerInput(
inputId = "val2"
,
label = "INDEPENDENT"
,
choices = colnames(iris)[-5] #all rows of selected column
,
multiple =T, options = list(`actions-box` = TRUE)
)
})
model <- eventReactive(c(input$val,input$val2),{
req(c(input$val,input$val2))
lm(as.formula(paste(input$val," ~ ",paste(input$val2,collapse="+"))),data=iris)
})
output$plot <- renderPrint({
summary(model())
})
output$plot2 <- renderggiraph({
ggPredict(model(),se=TRUE,interactive=TRUE)
})
output$plot3<-renderPlot({
ggplot(iris,aes(y=input$val,x=input$val2))+geom_point()+geom_smooth(method="lm")
})
}
)
You should use backticks to define the model variables if they contain spaces:
lm(as.formula(paste0("`",input$val,"` ~ ",paste0("`",input$val2,"`",collapse="+"))),data=iris)
This makes the model work.
However, this doesn't work properly with ggpredict because the backticks aren't saved in the model itself:
Looking at source of ggpredict shows that it seems difficult to overcome this difficulty without modifying the code of the function, see for example line 15 which causes the error above :
temp = paste0("aes(y=", yname, ",x=", xname)

RShiny: Refer to data from UI in server

Example Case: I have a function in my global.R called get_data which returns a list of many items. The reason I don't just put the data in global is so the data can automatically refresh after a certain amount of time
ui.R
my_data <- uiOutput("data") # Doesn't work
### Some more generic manipulation before final use
# The output of my_data will look like the following below.
my_data <- list()
my_data$first_entry <- c("a", "b", "d")
my_data$second_entry <- c("x", "y", "z") # and so on
shinyUI(navbarPage(theme=shinytheme("flatly"),
'App Name',
tabPanel('Title',
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
width=3,
# new box
checkboxGroupButtons(
'name',
'label:',
choices = sort(my_data$first_value),
status = 'primary',
selected = sort(my_data$first_value)[1],
size = 'xs'
# inline = TRUE
))
server.R
shinyServer(function(input, output, session) {
data <- reactive({
invalidateLater(100000,session)
get_data()
})
output$data <- renderUI({
data()
})
})
Two questions:
Is there any way of referencing my_data correctly?
If my function get_data is simply reading a (large) csv which is updated systematically. Is there a better way of doing it than I am currently doing it?
I think you're wondering how to define possible choices= for something within the UI element, when the data is both (1) undefined at the start, and (2) changing periodically. The answer to that is to define it "empty" and update it as the new data is found.
library(shiny)
library(shinyWidgets)
get_data <- function() as.list(mtcars[sample(nrow(mtcars), size=3), sample(ncol(mtcars), size=3)])
logg <- function(...) message(paste0("[", format(Sys.time()), "] ", ...))
shinyApp(
ui = fluidPage(
title = "Hello",
checkboxGroupButtons(inputId = "cb", label = "label:", choices = c("unk"), selected = NULL,
status = "primary", size = "xs"),
br(),
textOutput("txt"),
br(),
textAreaInput("txtarea", NULL, rows = 4)
),
server = function(input, output, session) {
data <- reactive({
logg("in 'data'")
invalidateLater(3000, session)
get_data()
})
observe({
logg("in 'observe'")
req(length(data()) > 0)
updateCheckboxGroupButtons(session = session, inputId = "cb", choices = names(data()))
updateTextAreaInput(session, "txtarea", value = paste(capture.output(str(data())), collapse = "\n"))
})
output$txt <- renderPrint({
logg("in 'txt'")
req(length(data()) > 0)
str(data())
})
}
)
Notice that the definition of checkboxGroupButtons starts with no real choices. I'd prefer to start it empty, but unlike selectInput and similar functions, it does not like starting with an empty vector. It is quickly (nearly-immediately) changed, so I do not see "unk" in the interface.
I demoed two options for "displaying" the data in its raw form: as an output "txt", and as an updatable input "txtarea". I like the latter because it deals well with fixed-width, but it requires an update* function (which is really not a big deal).

multiple updateSelectizeInput from filtered dataframe

This one has me really going around in circles.
I am working on an R script that loads a dataframe and uses fields from the dataframe to populate a hierarchical set of selectizeInput. E.g. each of the inputs represent a subset of what is in the previous. Each SubRegion contains multiple LCC’s, Each LCC contains multiple ENB’s, and so on.
When the user select a value in any of the inputs, that value will used to filter the dataframe and all of the other selectizeInputs need to be updated from the filtered data.
It seems to work fine for the first input (SubRegionInput) but every time I try to get it to respond to and/or filter by any of the others (e.g. add input$LCCInput to the observe block) they get populated for a few seconds and then go blank.
I suspect the answer is quite simple and/or I am doing something really dumb, but I am a total hack with no formal R training so am probably missing something quite basic (if so sorry).
Below is a partial chunk of code (sorry I can’t include it all but this is for work and I can’t share the details of what I am doing).
NOTES
The current outputs are just so I can see what is going on while I develop this portion of the code.
I know right now it is only set up to filter on the one value…everything I have tried to do it on more has failed so I included the most functional code I have so far.
ui <- fluidPage(
# Application title
titlePanel("KPI DrillDown"),
# Sidebar with a slider input for number of bins
fluidRow(
selectizeInput("SubRegionInput", "SubRegion", SubRegionList ,selected = NULL, multiple = TRUE),
selectizeInput("LCCInput", "LCC", LCCList,selected = NULL, multiple = TRUE),
selectizeInput("ENBIDInput", "ENBID", ENBIDList,selected = NULL, multiple = TRUE),
selectizeInput("SiteNumInput", "SiteNumber", SiteNumberList,selected = NULL, multiple = TRUE),
selectizeInput("SiteNameInput", "SiteName", SiteNameList,selected = NULL, multiple = TRUE),
selectizeInput("LNCELInput", "LNCell", LNCellList,selected = NULL, multiple = TRUE),
selectizeInput("SectorInput", "Sector", SectorList,selected = NULL, multiple = TRUE),
mainPanel(
#plotOutput("distPlot")
verbatimTextOutput("SubRegionText"),
verbatimTextOutput("LCCText"),
verbatimTextOutput("view")
)
)
)
server <- function(input, output) {
observe({
input$SubRegionInput
temp <- SiteInfo[SiteInfo$SITE_SUB_REGION %in% input$SubRegionInput, ]
thisLCCList = sort(temp$BACKHAUL_LCC[!is.na(temp$BACKHAUL_LCC)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "LCCInput"
, choices = thisLCCList
, selected= NULL)
thisENBIDList = sort(temp$ENODEB_ID[!is.na(temp$ENODEB_ID)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "ENBIDInput"
, choices = thisENBIDList
, selected= NULL)
thisSiteNumberList = sort(temp$SITE_NUMBER[!is.na(temp$SITE_NUMBER)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SiteNumInput"
, choices = thisSiteNumberList
, selected= NULL)
thisSiteNameList = sort(temp$SITE_NAME[!is.na(temp$SITE_NAME)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SiteNameInput"
, choices = thisSiteNameList
, selected= NULL)
thisLNCellList = sort(temp$SECTOR_NUMBER[!is.na(temp$SECTOR_NUMBER)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "LNCELInput"
, choices = thisLNCellList
, selected= NULL)
thisSectorList = sort(temp$Sector[!is.na(temp$Sector)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SectorInput"
, choices = thisSectorList
, selected= NULL)
output$view<- renderPrint(temp)
})
Since I do not have access to your data, I used mtcars as an example.
To begin with, since you have so many filtering, I would suggest creating a search or update button, which is what I did in my codes. I only did one filtering using dplyr after extracting all the selectizeInputs. I have to manually change all the empty searching parameter to select all in order to avoid filtering to NA.
Overall, I think the problem with your code was you are observing too many updateSelectizeInputs at once. I did try to recreate using your way, and what I ended with was that I could only update single selectizeInput, and the other selectizeInputs were not selectable.
Hopefully, this method fits your data.
Codes:
library(shiny)
library(dplyr)
library(DT)
data <- mtcars
SubRegionList <- unique(data$cyl)
LCCList <- unique(data$gear)
ENBIDList <- unique(data$am)
SiteNumberList <- unique(data$vs)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("KPI DrillDown"),
# Sidebar with a slider input for number of bins
fluidRow(
selectizeInput("SubRegionInput", "SubRegion/cyl", SubRegionList ,selected = NULL, multiple = TRUE),
uiOutput("LCCInput"),
uiOutput("ENBIDInput"),
uiOutput("SiteNumInput"),
uiOutput("Search"),
mainPanel(
verbatimTextOutput("view")
)
)
)
# Define server logic required
server <- function(input, output, session) {
SiteInfo <- data
# temp <- ""
observe({
if (!is.null(input$SubRegionInput)){
subRegionSelected <- input$SubRegionInput
## Create a temp dataset with the selected sub regions.
temp <- SiteInfo[SiteInfo$cyl %in% subRegionSelected, ]
## Push the newly created selectizeInput to UI
output$LCCInput <- renderUI({
selectizeInput("LCCInput", "LCC/gear", unique(temp$gear), selected = NULL, multiple = TRUE)
})
output$ENBIDInput <- renderUI({
selectizeInput("ENBIDInput", "ENBID/am", unique(temp$am),selected = NULL, multiple = TRUE)
})
output$SiteNumInput <- renderUI({
selectizeInput("SiteNumInput", "SiteNumber/vs", unique(temp$vs), selected = NULL, multiple = TRUE)
})
output$Search <- renderUI({
actionButton("Search", "Search")
})
## Function that linked to the actionButton
display <- eventReactive(input$Search,{
temp <- SiteInfo[SiteInfo$cyl %in% input$SubRegionInput, ]
# ## manually change all the empty searching parameter to select all in order to avoid filtering to NA
LCC <- input$LCCInput
if (is.null(input$LCCInput)){LCC <- unique(temp$gear)}
ENBID <- input$ENBIDInput
if (is.null(input$ENBIDInput)){EBVID <- unique(temp$am)}
SiteNum <- input$SiteNumInput
if (is.null(input$SiteNumInput)){LCC <- unique(temp$vs)}
## Dplyr::filter data
temp <- temp %>%
filter(gear %in% LCC & am %in% ENBID & vs %in% SiteNum)
temp
})
## Run the actionButton
output$view <- renderPrint({
display()
})
} else {
## Display waht the data looks like when no Sub Region is selected
output$view<- renderPrint(data)
}
})
}
# Run the application
shinyApp(ui = ui, server = server)

Resources