使用dateInput值将数据帧子集设置为闪亮范围

时间:2018-02-28 18:50:59

标签: date shiny reactive

您好我在下面有一个简单的闪亮应用程序。这是df

location = c("100 ail","16th and Whitmore","40AB01 - ANTWERPEN","100 ail","16th and Whitmore","40AB01 - ANTWERPEN") 
date = c("2015-09-01 00:00:00","2016-03-06 19:00:00","2016-11-22 15:00:00","2018-02-01 09:30:00", "2018-02-01 03:00:00", "2017-03-07 10:00:00") 
pm25=c("FALSE","FALSE","FALSE","FALSE","FALSE","FALSE")
pm10=c("TRUE","FALSE","FALSE","TRUE","FALSE","FALSE")
no2=c("TRUE","FALSE","FALSE")
latitude=c(47.932907,41.322470,36.809700,47.932907,41.322470,36.809700)
longitude=c(106.92139000,-95.93799000
            ,-107.65170000,106.92139000,-95.93799000
            ,-107.65170000)

df = data.frame(location, date,latitude,longitude,pm25,pm10,no2)

和app:

ui = fluidPage(

  uiOutput("dt"),
  uiOutput("dt2"),
  submitButton(text = "Submit", icon = NULL, width = NULL),
  shiny::dataTableOutput("merged") 
)

#server.r

#df$location <- gsub( " " , "+" , df$location)
server = function(input, output, session) {







  output$dt<-renderUI({

    dateInput('date',
              label = 'First Available Date',
              value = df$date
    )           


  })
  output$dt2<-renderUI({

    dateInput('date2',
              label = 'Last available Date',
              value = df$date
    )            


  })
  output$merged <- shiny::renderDataTable({
    df %>%
      filter(date >= input$dt & date <= input$dt2)
  })
}

shinyApp(ui = ui, server = server)

我希望显示为数据表的df应该将2 selectInput()作为范围提供的日期作为输入,并在每次更新时更改其外观。可以这样做吗?或dateInput()只显示从头开始所需的数据,不能用于子集化?

1 个答案:

答案 0 :(得分:1)

首先,您需要将date列转换为date格式。 (为此,我使用了lubridate

library(lubridate)

df = data.frame(location, date = as_datetime(date),latitude,longitude,pm25,pm10,no2)

在这种情况下,不需要使用renderUI,因为您的数据不是动态的。 (它也像这样工作,只是不理想)。我只想使用dateInput

dateInput('date',
            label = 'First Available Date',
            value = min(df$date)
)   ,
dateInput('date2',
          label = 'Last available Date',
          value = max(df$date)
)

另外,dateInput设置value = df$date会产生警告,因为value参数只有一个值,但df$date长度为vector 6.所以我改为min(df$date)max(df$date)

render功能中,您需要指定id的{​​{1}},因此请使用dateInputinput$date代替input$date2 }和dt

注意:使用 dplyr dt2时:不需要运算符filter,您只需用逗号分隔过滤条件即可。

&

还有一件事:我选择使用df %>% filter(as_date(date) >= input$date, as_date(date) <= input$date2) date_time转换为date进行过滤。如果您将as_date(date)date进行比较,则可能会出现意外结果,例如date_time大于2017-03-12 02:00

完整代码:

2017-03-02