I'm trying to build a page using R Shiny that has:
A File Widget for uploading CSV files
A Checkbox Group component
I'd like to use these as follows:
Upon uploading a valid CSV file, populate the CheckBox group whose checkboxes are all the headers from the CSV file, all checked by default
I've tried various forms of observe() and observeEvent() so far, but have had no success in getting this even close. Any suggestions you may have would be great.
You may try checkboxGroupInput.
library(shiny)
ui <- fluidPage(
fileInput('file', 'Upload csv file'),
uiOutput('dropdown')
)
server <- function(input, output) {
data <- reactive({
req(input$file)
read.csv(input$file$datapath)
})
output$dropdown <- renderUI({
req(data())
checkboxGroupInput('cols', 'Select Column', names(data()),
names(data()), inline = TRUE)
})
}
shinyApp(ui, server)
You can set inline = FALSE if you want to arrange them vertically.
Related
I'm trying to build a page using R Shiny that has:
A File Widget for uploading CSV files
A SelectInput component
I'd like to use these as follows:
Upon uploading a valid CSV file, populate the SelectInput whose options are the headers from the CSV file, the first header being the default selected
I've tried various forms of observe() and observeEvent() so far, but have had no success in getting this even close. Any suggestions you may have would be great.
Here's an option -
library(shiny)
#Sample data
#write.csv(mtcars, 'data.csv', row.names = FALSE)
ui <- fluidPage(
fileInput('file', 'Upload csv file'),
uiOutput('dropdown')
)
server <- function(input, output) {
data <- reactive({
req(input$file)
read.csv(input$file$datapath)
})
output$dropdown <- renderUI({
req(data())
selectInput('cols', 'Select Column', names(data()))
})
}
shinyApp(ui, server)
I have a Shiny app that wrangles a large csv file. Currently the user can select a facility_id number from a drop down menu to get a specific plot, see https://r.timetochange.today/shiny/Annual_Emissions2/. I would like to pass this id with a URL parameter like /?selected_facilities=1010040 so I can embed the plots in another website.
I have taken the code from How do you pass parameters to a shiny app via URL and tried to use it to update my selectInput() value in the server section of the Shiny app, but I don't really understand how the UI part is constructed so I am not getting it right. Any help would really be appreciated! Here is the relevant code:
#### shiny UI ####
facilities <- unique(ghg_emissions$facility_id)
ui <- fluidPage(
titlePanel("Annual Greenhouse Gas Emissions"),
sidebarLayout(
sidebarPanel(
selectInput("selected_facility",
"Select facility",
choices = facilities) # select input gives the drop down menu to select facilities
),
mainPanel(
plotlyOutput("facility_plot")
)
)
)
#### shiny server ####
server <- function(input, output, session) {
# Here you read the URL parameter from session$clientData$url_search
observe({
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query[['selected_facility']])) {
updateSelectInput(session, "selected_facility", value = query[['selected_facility']])
}
})
Your UI is good, the issue with the updateSelectInput, use selected rather than value and include choices.
Minimal working example:
library(shiny)
facilities <- seq(1:5)
ui <- fluidPage(
selectInput("selected_facility", "Select facility", choices = facilities)
)
server <- function(input, output, session) {
observe({
#Get URL query
query <- parseQueryString(session$clientData$url_search)
#Ignore if the URL query is null
if (!is.null(query[['selected_facility']])) {
#Update the select input
updateSelectInput(session, "selected_facility", selected = query[['selected_facility']], choices = facilities)
}
})
}
shinyApp(ui, server)
To test, run your shiny app, click 'Open in Browser' and append your query to the URL, e.g.
127.0.0.1:6054/?selected_facility=4
I am learing Shiny. I want to make a simple app that allows for dynamic paths that the user enters. The app should then list csv files in folder A and then copy them from folder A to folder B (the working directory). Then the app does some operations in folder B using an external exe program. Afterwards the folder will cut the results files (.txt) from B and copies them into A.
The structure of my app is as follows ( I have also attached a picture). the problem is explained in the comments in the code.
library(shiny)
ui<-fluidPage(
textInput("prg","Program",getwd()),
verbatimTextOutput("prg"),
textInput("prj","Project","Project"),
verbatimTextOutput("prj")
)
server<-function(input, output,session) {
output$prg=renderText(input$prg)
renderPrint(output$prg)
output$prj=renderText(paste0(input$prg,"/",input$prj))
#This is where my challenge is
#I want to
#list.files(path=path-shown-in-text-box-Project,pattern=".csv")
#Then i want to copy csv files from A to B as described above and run the following program
#This works
observeEvent(input$run,
{
system("my.exe") #exe not shared
})
#Finally I want to cut and paste the results (.txt) from B back into A
}
shinyApp(ui,server)
I want to list.files(path=path-shown-in-text-box-Project,pattern=".csv")
Here's code you can use to browse any directory for a particular CSV file, read that file and display its contents.
library(shiny)
# Define UI
ui <- pageWithSidebar(
# App title ----
headerPanel("Open a File and Show Contents"),
# Sidebar panel for inputs ----
sidebarPanel(
label="Data Source",fileInput("fileName", "File Name",accept=c(".csv"))),
# Main panel for displaying outputs ----
mainPanel(
tableOutput(outputId = "table")
)
)
# Define server logic
server <- function(input, output) {
inputData <- reactive ({
if (is.null(input$fileName)) return(NULL)
inFile <- input$fileName
conInFile <- file(inFile$datapath,open='read')
inData <- read.csv(conInFile,stringsAsFactors = FALSE)
close (conInFile)
return (inData)
})
output$table <- renderTable ({
inData <- inputData()
if (length(inData) > 0) inData
})
}
shinyApp(ui, server)
I am trying to create a UI on which I can upload a file and also there is a text input where I can write the product name which I want to search in the uploaded file. I am doing that using the Levenshtein Distance function (adist() function). Now, once i get the results for which the edit distance is 0, I want to display those rows in the Table on the Main Panel. Whatever input is given in the Text input on the UI is searched against the items column in the file uploaded. A sample image of the CSV file which is uploaded is this-
Sample image of the CSV file which is input by the user
Once I run the code and find the edit distance for all the words, I store them in a vector and then use this to print the rows from the file which have edit distance equal to 0. The problem is that when I click on submit, the result is not displayed on the UI but it is displayed on the R-studio console. How do I fix this?
Please help me with the code.
library(shiny)
ui = shinyUI(fluidPage(
titlePanel("LEVENSHTEIN DISTANCE function trial"),
sidebarLayout(
sidebarPanel(
numericInput("rows","Enter the number of rows",value=NULL),
textInput("product", "input product name"),
br(),
br(),
fileInput("file", "Input the file"),
submitButton("Find!")),
mainPanel(
tableOutput("result")
)
)
))
server = shinyServer(function(input,output) {
output$result <- renderPrint({ if (is.null(input$file)) return( );
trial = read.csv(input$file$datapath)
ls = vector('list', length = input$rows)
for(i in 1:input$rows) {
edit = adist("earbuds", trial$items[i])
new_edit = as.numeric(edit)
ls[i] = edit
if(ls[i]==0) print(trial[i, ])
}
})
})
shinyApp(ui=ui,server=server)
Thank You!
It is very hard to provide working code without sample input date. But, here is my attempt at giving you what I think should work.
server = shinyServer(function(input,output) {
output$result <- renderTable({
if (!is.null(input$file)) {
trial = read.csv(input$file)
trial <- trial[adist('earbuds', trial$items) == 0), ]
}
})
})
If you provide input data and expected output table, I can edit the answer to be more precise.
In shiny, how do you use tagList inside renderUI to create multiple widgets customized with data from an uploaded file? This idea is referenced here, but there doesn't appear to be very good documentation for tagList.
I plan to answer my own question here. I did a bit of research, found that a simple example of this process was lacking, and felt a desire to contribute it so that others might benefit.
In server.R, define an object using a reactive() statement to hold the contents of the uploaded file. Then, in a renderUI statement, wrap a comma-delimited list of widget definitions in a tagList function. In each widget, use the object holding the contents of the uploaded file for the widget parameters. The example below, hosted at shinyapps.io and available on github, creates a checkBoxGroupInput and a radioButtons widget using a singer renderUI that is defined based on an uploaded file.
server.R
library(shiny)
shinyServer(function(input, output) {
ItemList = reactive(
if(is.null(input$CheckListFile)){return()
} else {d2 = read.csv(input$CheckListFile$datapath)
return(as.character(d2[,1]))}
)
output$CustomCheckList <- renderUI({
if(is.null(ItemList())){return ()
} else tagList(
checkboxGroupInput(inputId = "SelectItems",
label = "Which items would you like to select?",
choices = ItemList()),
radioButtons("RadioItems",
label = "Pick One",
choices = ItemList(),
selected = 1)
)
})
})
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Create a checkboxGroupInput and a RadioButtons widget from a CSV"),
sidebarLayout(
sidebarPanel(fileInput(inputId = "CheckListFile", label = "Upload list of options")),
mainPanel(uiOutput("CustomCheckList")
)
)
))