2017-02-14 9 views
1

Я пытался выяснить, как подключить несколько входов с одним выходным объектом в Shiny.Несколько текстовых входов Shiny R

У меня есть таблица как результат, и я хочу показывать только определенные строки этой таблицы в зависимости от того, что пользователь вводит в текстовое поле. В моем примере таблица имеет столбцы: имя, адрес, дата, время, идентификатор, следующее назначение.

Я фильтрую вход пользователя на основе регулярных выражений, который отлично работает, но он ломается при попытке дифференцировать DateOfBirth и NextAppointment, поскольку они являются ГГГГ-ММ-ДД.

Как создать новый ввод текста, который не будет мешать первому? Я не могу заставить это работать. Нужно ли использовать что-то другое, кроме кнопки отправки?

Моя программа прямо сейчас будет искать только в соответствии с первым полем ввода текста. Второй блок ввода текста не активен. Здесь мне нужна ваша помощь.

Большое спасибо за внимание. Вот мой пример кода приложения:

library(shiny) 

#ui.R 
#-------------------------------------------------------------------- 
ui = shinyUI(pageWithSidebar(
    headerPanel("Test App"), 
    sidebarPanel(
    #declare 2 text inputs and submit button 
    textInput(inputId = "variableInput", label = "Search by Name, ID or Date of Birth"), 
    textInput(inputId = "NextAppt", "Search by Next Appointment"), 
    submitButton(text = "Submit") 
), 
    mainPanel(
    #declare text output(s) 
    #I don't want to have 2 table outputs 
    #ideally I would have 2 search boxes for 1 table 
    tableOutput("Variable") 
    #,tableOutput("NextAppt") 
) 
)) 


#server.R 
#-------------------------------------------------------------------- 
server = shinyServer(function(input, output){ 
    #make sample table with values. each vector represents a column 
    Name = c("Person1", "Person2", "Person3") 
    Address = c("101 E St", "102 E St", "103 E St") 
    DateOfBirth = c("1990-01-01", "1990-01-02", "1990-01-03") 
    ID = c("12345", "23456", "34567") 
    NextAppointment = c("2017-02-14", "2017-02-15", "2017-02-16") 
    df = data.frame(Name, Address, DateOfBirth, ID, NextAppointment) 

    #determine what the user is searching for by using regular expressions 
    #if the user entered something like ####-##-##, where # is any number, 
    #then they must have entered a date 
    #if the user enters #####, then it must be an ID 
    #otherwise, they entered a name 
    #search.criteria() is a vector of the rows of our dataframe to display 
    search.criteria <- reactive({ 
    if(grepl("\\d{4}\\-\\d{2}\\-\\d{2}", input$variableInput)==TRUE){ 
     which(df$DateOfBirth==input$variableInput) 
    } else if(grepl("\\d{5}", input$variableInput)==TRUE){ 
     which(df$ID==input$variableInput) 
    } else{ 
     which(df$Name==input$variableInput) 
    } 
    }) 

    #create output table 
    output$Variable = renderTable({ 
    df[search.criteria(), ] #use the search.critera() reactive to determine rows to display 
    }) 

}) 


#app.R 
#-------------------------------------------------------------------- 
shinyApp(ui, server) 
+0

Если DateOfBirth и NextAppointment не перекрывают друг друга, вы можете добавить правило для выбора поля для фильтрации – HubertL

ответ

1

Будет ли это работать на вас?

library(shiny) 

#ui.R 
#-------------------------------------------------------------------- 
ui = shinyUI(pageWithSidebar(
    headerPanel("Test App"), 
    sidebarPanel(
    #declare 2 text inputs and submit button 
    textInput(inputId = "variableInput", label = "Search by Name, ID, Date of Birth"), 
    textInput(inputId = "NextAppt", label = "Next Appointment"), 
    submitButton(text = "Submit") 
), 
    mainPanel(
    #declare text output(s) 
    #I don't want to have 2 table outputs 
    #ideally I would have 2 search boxes for 1 table 
    tableOutput("Variable") 
    #,tableOutput("NextAppt") 
) 
)) 


#server.R 
#-------------------------------------------------------------------- 
server = shinyServer(function(input, output){ 
    #make sample table with values. each vector represents a column 
    Name = c("Person1", "Person2", "Person3") 
    Address = c("101 E St", "102 E St", "103 E St") 
    DateOfBirth = c("1990-01-01", "1990-01-02", "1990-01-03") 
    ID = c("12345", "23456", "34567") 
    NextAppointment = c("2017-02-14", "2017-02-15", "2017-02-16") 
    df = data.frame(Name, Address, DateOfBirth, ID, NextAppointment) 

    #determine what the user is searching for by using regular expressions 
    #if the user entered something like ####-##-##, where # is any number, 
    #then they must have entered a date 
    #if the user enters #####, then it must be an ID 
    #otherwise, they entered a name 
    #search.criteria() is a vector of the rows of our dataframe to display 
    search.criteria <- reactive({ 
    out <- c() 
    outAppt <- c() 
    if(grepl("\\d{4}\\-\\d{2}\\-\\d{2}", input$variableInput)==TRUE){ 
     out <- which(df$DateOfBirth==input$variableInput) 
     print(out) 
    } else if(grepl("\\d{5}", input$variableInput)==TRUE){ 
     out <- which(df$ID==input$variableInput) 
    } else{ 
     out <- which(df$Name==input$variableInput) 
    } 
    # filter for appointment 
    if(grepl("\\d{4}\\-\\d{2}\\-\\d{2}", input$NextAppt)==TRUE){ 
     outAppt <- which(df$NextAppointment==input$NextAppt) 
     if(length(out)){ 
     out <- intersect(out, outAppt) 
     }else{ 
     out <- outAppt 
     } 
    } 
    out 
    }) 

    #create output table 
    output$Variable = renderTable({ 
    print(search.criteria()) 
    df[search.criteria(), ] #use the search.critera() reactive to determine rows to display 
    }) 

}) 


#app.R 
#-------------------------------------------------------------------- 
shinyApp(ui, server) 
+0

Большое спасибо за ваш ответ. Я вижу, что вы делали, но по-прежнему кажется, что он не совсем работает. По какой-то причине поиск фактически не выполняется, когда я только что-то вводил в поле поиска «Next Appointment». Ничего не произошло. Может ли это быть, потому что кнопка отправки привязана только к первому ящику ввода? Я не уверен. Еще раз заблаговременно за вашу помощь. – tsouchlarakis

+0

В поле поиска «Следующее назначение» больше нет. в моей версии, я не уверен, что понимаю проблему:/ – BigDataScientist

+0

Вы правы! Это была моя вина. Это работает, объединяя все в один блок поиска. Спасибо за помощь! – tsouchlarakis