在常规R函数中找不到数据集(reactiveValue)

时间:2017-05-30 20:40:58

标签: r shiny

我有一个数据集(称为mydata $ data),我希望一直保持更新。首先,该数据集以< rawdata'形式读入。然后由几个常规R函数更新。

以下是我的代码。当我运行应用程序时,我总是收到此错误。

Warning: Error in <-: object 'mydata' not found
Stack trace (innermost first):
    106: PrepareData [./functions-sample.R#2]

有人可以帮忙吗?我该如何定义该数据集?如何使用常规R函数更新它?

RAWDATA:

colA <- c('A','B','C','D','E')
colB <- c(1,2,3,4,5)
rawdata <- as.data.frame(cbind(colA,colB))
View(rawdata)

ui.R:

fluidPage(
  sidebarPanel(
    actionButton("runButton", strong("Run!"))
  ),
  mainPanel(
    tabsetPanel(id = "allResults",
              tabPanel(value='inputVars',title='Variable', DT::dataTableOutput('inputVars')),
              tabPanel(value='result',title='Result', DT::dataTableOutput('result')),
              tabPanel(value='temp',title="TEMP", verbatimTextOutput("temp"))
    )
  )
)

server.R:

source("./functions-sample.R")

function(input, output, session) {

  # Activate tab 'Result' when users click 'Run'
  observeEvent(input$runButton, {
    updateTabsetPanel(session, "allResults", 'result')
  })

  mydata <- reactiveValues()

  ### RESULT TAB ###

  # mydata$data is the active dataset we want to keep updating
  result <- eventReactive (input$runButton, {
    mydata$data <- rawdata
    PrepareData(mydata$data)
    head(mydata$data,5)
  })

  ### RENDERING FUNCTIONS ###

  # Default SummaryTable
  output$inputVars <- DT::renderDataTable({
      DT::datatable(rawdata, options = list(paging = FALSE, searching = FALSE))
  })

  # Display results
  output$result <- DT::renderDataTable({
    DT::datatable(result(), options = list(paging = FALSE, searching = FALSE))
  })

  output$temp <- renderPrint({
    print(head(mydata$data))
  })
}

功能-sample.R:

PrepareData<-function(datax) {
  mydata$data <- RankData(datax)
  CodeMissingData(mydata$data)
}

RankData<-function(datax) {
  return(datax[order(datax[,1],datax[,2]),])
}

CodeMissingData<-function(datax) {
  for (v in 4:ncol(datax)) {
    if (!("*NA*" %in% levels(datax[,v]))) {levels(datax[,v])<<-c(levels(datax[,v]),"*NA*")}
  }
  datax[,-(1:3)][is.na(datax[,-(1:3)]) | datax[,-(1:3)]=="NA"]<<-"*NA*"
  mydata$data <- datax
}

1 个答案:

答案 0 :(得分:2)

尝试从函数返回数据而不是修改它:

CodeMissingData<-function(datax) {
  for (v in 4:ncol(datax)) {
    if (!("*NA*" %in% levels(datax[,v]))) {levels(datax[,v])<-c(levels(datax[,v]),"*NA*")}
  }
  datax[,-(1:3)][is.na(datax[,-(1:3)]) | datax[,-(1:3)]=="NA"]<-"*NA*"
  return(datax)
}

PrepareData<-function(datax) {
  CodeMissingData(RankData(datax))
}

然后在server.R

 result <- eventReactive (input$runButton, {
    mydata$data <- PrepareData(rawdata)
    head(mydata$data,5)
  })