在Shiny App中使用超前/滞后

时间:2016-03-16 20:30:16

标签: r ggplot2 shiny dplyr

我觉得这个问题适用于关于如何在Shiny上下文中操作数据的一般查询,但我的具体问题与 $http.get(/**/).then(function(response) { // do something with response }).catch(function(err) { // do something with error err }) 中的超前/滞后函数的使用有关。现在我面临两个问题。

第一个问题是在数据集中定义setState的变量。我使用dplyr方法命名滞后变量lead/lag。由于R无法找到dplyr,因此这是不正确的。那么有人可以推荐一种更改/创建变量的方法,以便通过闪亮的应用程序向下传输结果并可以调用吗?

第二个问题是指定引导/滞后Y变量的行数。在ui.R文件中很容易指定一个带有超前/滞后位置的输入框。但是,如何将该输入框中的整数作为参数放在yvar函数中?

这是 ui.R

yvar

这是 server.R

lead

1 个答案:

答案 0 :(得分:3)

我认为这就是你想要的。为了让它工作,我做了以下事情:

  • 放弃了mutate,因为使用动态名称显然非常困难(请参阅:R - dplyr - mutate - use dynamic variable names),只是按照建议使用数据框索引进行。
  • 将它合并到一个文件中,这样我就可以立刻看到所有内容(适合小东西)
  • 添加了print语句以在每次更改时转储数据集,以便您可以查看发生的情况。
  • yvar变量中添加引号,以便它与aesstring
  • 一起使用
  • as.numeric添加到offset变量作为lead
  • 的输入

这是结果代码:

library(shiny)
library(ggplot2)
library(dplyr)

dataset <- iris

u <- shinyUI(pageWithSidebar(
  headerPanel("Iris Data Explorer"),
  sidebarPanel(
    selectInput('x', 'X', names(dataset), names(dataset)[[2]]),
    selectInput('y', 'Y', names(dataset), names(dataset)[[4]]),
    selectInput('offset', 'Offset Level of Y', 0:5, 0),
    selectInput('species', 'Species', levels(dataset$Species), "virginica")
  ),
  mainPanel(
    plotOutput('plot')
  )
))
s <- shinyServer(function(input, output) {
  dataset <- reactive({
    df <- iris %>% filter(Species==input$species) 
    df[["yvar"]] <- lead(df[[input$y]],as.numeric(input$offset))
    return(df)
  })
  output$plot <- renderPlot({
    dataset<-dataset()
    print(dataset)
    ggplot(dataset, aes_string(x=input$x,y="yvar")) + geom_point(na.rm=T) 
  }, height=500)
})
shinyApp(ui=u,server=s)

这就是它的样子: enter image description here