使用R闪亮将(多个)值添加到数据框

时间:2014-10-17 14:21:36

标签: r shiny

我正在将R shiny与ggplot结合使用来可视化某个数据集。我希望用户能够为此数据集添加值。我可以得到我的应用程序,以便向我显示原始数据+一个数据点,但是一旦用户输入新点,旧的点就消失了:用户输入的数据实际上并不存储在我的数据帧中。 / p>

我正在使用的一些代码(为简单起见,更改了变量名称):

shinyServer(
  function(input, output) {     
    output$newPlot <- renderPlot({   
      input$addButton
      isolate({
        x <- as.numeric(input$x)
        y <- as.numeric(input$y)
        if (!is.na(y)) {
          data <- rbind(data, data.frame(x = x, y = y))

          # more code here

        }

        # more code here 

        plot <- myPlot(data)
        print(plot)

      })
    })
  }
)

用户可以使用textInput为x和y赋值,然后使用按钮(actionButton)提交这些值。每次用户点击“添加”时,最近输入的x和y值显示在原始数据的顶部,但是用户输入的(在同一会话中)的任何其他值都将丢失。如何记住我的用户输入并绘制所有内容?

1 个答案:

答案 0 :(得分:3)

我无法根据您提供的代码专门复制您的内容,但也许一个例子可以帮助您。您需要的部分是reactiveValues,这允许您存储数据集并在整个会话中根据需要更新它。也许这可以帮助您解决问题?

require(shiny)
data(iris)

runApp(
  list(
    ui = fluidPage(
      headerPanel('Adding Data'),
      sidebarPanel(
        textInput("species", label="Add a new species", value="Enter species"),
        numericInput("sepal.length", label="Add a new sepal length", value=""),
        numericInput("sepal.width", label="Add a new speal width", value=""),
        numericInput("petal.length", label="Add a new petal length", value=""),
        numericInput("petal.width", label="Add a new petal width", value=""),
        actionButton("addButton", "UPLOAD!")
      ),
      mainPanel(
        tableOutput("table"))
    ),

    server = function(input, output) {     
      # just a small part of iris for display
      iris_sample <- iris[sample(nrow(iris), 10),]
      row.names(iris_sample) <- NULL

      # The important part of reactiveValues()
      values <- reactiveValues()
      values$df <- iris_sample
      observe({

        # your action button condition
        if(input$addButton > 0) {
          # create the new line to be added from your inputs
          newLine <- isolate(c(input$sepal.length, input$sepal.width, input$petal.length, input$petal.width, input$species))
          # update your data
          # note the unlist of newLine, this prevents a bothersome warning message that the rbind will return regarding rownames because of using isolate.
          isolate(values$df <- rbind(as.matrix(values$df), unlist(newLine)))
        }
      })
      output$table <- renderTable({values$df}, include.rownames=F)
    }
  )
)