【问题标题】:Two Reactives Error Invalid Argument to Unary Operator一元运算符的两个反应错误无效参数
【发布时间】:2017-04-08 09:40:54
【问题描述】:

我正在尝试构建一个以表格格式显示 .csv 文件的应用程序。用户可以使用单选按钮选择两种显示表格的方式之一。我已经用filedata()data_ranked_words() 反应器定义了这两种方式。

要重现此错误,请先运行此代码块以获取我的一小部分数据:

test = rbind(
  c(0.00000009, 0.00000009, 0.00046605, 0.00015541, 0.00215630),
  c(0.00000016, 0.00137076, 0.00000016, 0.00000016, 0.00000016),
  c(0.00012633, 0.00000014, 0.00000014, 0.00000014, 0.00075729),
  c(0.00000013, 0.00000013, 0.00000013, 0.00000013, 0.00062728)
  )
colnames(test) = c('church', 'appearance', 'restrain', 'parity', 'favor')
rownames(test) = NULL
test = as.data.frame(test)
write.csv(test, 'test.csv', row.names = FALSE)

程序一启动,您就会看到Error invalid argument to binary operator。然后在工作目录中从文件系统中选择test.csv,您将看到在选择“Word View”时错误仍然存​​在,但在选择“Probability View”时表格正确显示。

这个应用程序非常简单。问题出现在第 66 行temp = matrix(row.names(data)[apply(-data, 2, order)], nrow(data))。它不喜欢apply 中的-data。但是,尽我所能,我无法在闪亮之外的 R 控制台中重现此错误。在常规 R 中,这条线运行得很好。

我要做的是在用户选择单选按钮时显示两个不同的表格。 “概率视图”是原始表,“字视图”是带有一些操作的表(第 61-71 行)。这个我想不通!

这是我的应用程序:

library(shiny)
library(markdown)
library(DT)
library(D3TableFilter)
options(shiny.maxRequestSize=50*1024^2) 

# ui.R
#-------------------------------------------------------------------------------------
ui <- shinyUI(
  navbarPage("Topic Model App v1.0",
             tabPanel("From CSV",
                      sidebarLayout(
                        sidebarPanel(
                          # Define what's in the sidebar
                          fileInput("file",
                                    "Choose CSV files from directory",
                                    multiple = TRUE,
                                    accept=c('text/csv', 
                                             'text/comma-separated-values,text/plain', 
                                             '.csv')),
                          radioButtons('toggle', 'Choose one:',
                                       list('Word View', 'Probability View'))
                          ),
                        # Define what's in the main panel
                        mainPanel(
                          title = 'Topic Model Viewer',
                          # How wide the main table will be
                          fluidRow(
                            column(width = 12, d3tfOutput('data'))
                          )
                        )
                      )
                  )
             )
)


# server.R
#-------------------------------------------------------------------------------------
server <- shinyServer(function(input, output, session) {
  # Set up the dataframe for display in the table
  # Define 'filedata()' as the .csv file that is uploaded
  filedata <- reactive({
    infile <- input$file
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }
    # Read in .csv file and clean up
    data = read.csv(infile$datapath)
    data = t(data)
    data = as.data.frame(data)
    colnames(data) = paste0(rep('topic', ncol(data)), 1:ncol(data))
    data = format(data, scientific = FALSE)

    data
  })

  #PROBLEM
  # The ranked and ordered csv file
  data_ranked_words <- reactive({
    # Sort each column by probability, and substitute the correct word into that column
    # This will essentially rank each word for each topic
    # This is done by indexing the row names by the order of each column
    data = filedata()
    temp = matrix(row.names(data)[apply(-data, 2, order)], nrow(data))
    temp = as.data.frame(temp)
    colnames(temp) = paste0(rep('topic', ncol(data)), 1:ncol(data))

    temp
  })

  # Create table
  output$data <- renderD3tf({
    tableProps <- list(
      rows_counter = TRUE,
      rows_counter_text = "Rows: ",
      alternate_rows = TRUE
    );

    # Radio buttons
    # The reason why the extensions are in this if() is so that sorting can be
    # activated on Probability View, but not Word View
    if(input$toggle=='Word View'){
      df = data_ranked_words()
      extensions <-  list(
        list( name = "colsVisibility",
              text = 'Hide columns: ',
              enable_tick_all =  TRUE
        ),
        list( name = "filtersVisibility",
              visible_at_start =  FALSE)
      )
    } else if(input$toggle=='Probability View'){
      df = filedata()
      extensions <-  list(
        list(name = "sort"),  #this enables/disables sorting
        list( name = "colsVisibility",
              text = 'Hide columns: ',
              enable_tick_all =  TRUE
        ),
        list( name = "filtersVisibility",
              visible_at_start =  FALSE)
      )
    }

    if(is.null(filedata())){
    } else{
      d3tf(df,
           tableProps = tableProps,
           extensions = extensions,
           showRowNames = TRUE,
           tableStyle = "table table-bordered")
    }
  })



  # This line will end the R session when the Shiny app is closed
  session$onSessionEnded(stopApp)
})

# Run app in browser
runApp(list(ui=ui,server=server), launch.browser = TRUE)

【问题讨论】:

    标签: r csv shiny r-markdown


    【解决方案1】:

    因此,这里有几个问题相互影响,使事情难以诊断:

    • 在定义数据之前它正在运行并尝试执行。避免这种情况的“现代”方法是使用req(input$file) - 现在已插入filedata 反应式。请注意,这将中断整个链的执行,直到在闪亮的 ui 中定义 input$file
    • data = format(data, scientific = FALSE) 正在将您的列转换为“AsIs”类型的向量,而单一减号命令不知道如何对其进行操作。现在被filedata()注释掉了。
    • 为了恢复抑制科学记数法的功能,在 d3tf 中显示之前,将其移动到 dffiledata() 创建的位置之后。
    • 注意:我发现 optionsscipen 在这里不起作用。不知道为什么会这样,但是这个 AsIs 类可以解决问题。

    调整后的代码如下:

    library(shiny)
    library(markdown)
    library(DT)
    library(D3TableFilter)
    options(shiny.maxRequestSize=50*1024^2) 
    
    # ui.R
    #-------------------------------------------------------------------------------------
    ui <- shinyUI(
      navbarPage("Topic Model App v1.0",
                 tabPanel("From CSV",
                          sidebarLayout(
                            sidebarPanel(
                              # Define what's in the sidebar
                              fileInput("file",
                                        "Choose CSV files from directory",
                                        multiple = TRUE,
                                        accept=c('text/csv', 
                                                 'text/comma-separated-values,text/plain', 
                                                 '.csv')),
                              radioButtons('toggle', 'Choose one:',
                                           list('Word View', 'Probability View'))
                            ),
                            # Define what's in the main panel
                            mainPanel(
                              title = 'Topic Model Viewer',
                              # How wide the main table will be
                              fluidRow(
                                column(width = 12, d3tfOutput('data'))
                              )
                            )
                          )
                 )
      )
    )
    
    
    # server.R
    #-------------------------------------------------------------------------------------
    server <- shinyServer(function(input, output, session) {
      # Set up the dataframe for display in the table
      # Define 'filedata()' as the .csv file that is uploaded
      filedata <- reactive({
        req(input$file)
        infile <- input$file
        if (is.null(infile)) {
          # User has not uploaded a file yet
          return(NULL)
        }
        # Read in .csv file and clean up
        data = read.csv(infile$datapath)
        data = t(data)
        data = as.data.frame(data)
        colnames(data) = paste0(rep('topic', ncol(data)), 1:ncol(data))
    #    data = format(data, scientific = FALSE)
    
        data
      })
    
      #PROBLEM
      # The ranked and ordered csv file
      data_ranked_words <- reactive({
        # Sort each column by probability, and substitute the correct word into that column
        # This will essentially rank each word for each topic
        # This is done by indexing the row names by the order of each column
        data = filedata()
        temp = matrix(row.names(data)[apply(-data, 2, order)], nrow(data))
        temp = as.data.frame(temp)
        colnames(temp) = paste0(rep('topic', ncol(data)), 1:ncol(data))
    
        temp
      })
    
      # Create table
      output$data <- renderD3tf({
        tableProps <- list(
          rows_counter = TRUE,
          rows_counter_text = "Rows: ",
          alternate_rows = TRUE
        );
    
        # Radio buttons
        # The reason why the extensions are in this if() is so that sorting can be
        # activated on Probability View, but not Word View
        if(input$toggle=='Word View'){
          df = data_ranked_words()
          extensions <-  list(
            list( name = "colsVisibility",
                   text = 'Hide columns: ',
                  enable_tick_all =  TRUE
            ),
            list( name = "filtersVisibility",
                  visible_at_start =  FALSE)
          )
        } else if(input$toggle=='Probability View'){
          df = filedata()
          df = format(df, scientific = FALSE)
          extensions <-  list(
            list(name = "sort"),  #this enables/disables sorting
            list( name = "colsVisibility",
                  text = 'Hide columns: ',
                  enable_tick_all =  TRUE
            ),
            list( name = "filtersVisibility",
                  visible_at_start =  FALSE)
          )
        }
    
        if(is.null(filedata())){
        } else{
          d3tf(df,
               tableProps = tableProps,
               extensions = extensions,
               showRowNames = TRUE,
               tableStyle = "table table-bordered")
        }
      })
    
    
    
      # This line will end the R session when the Shiny app is closed
      session$onSessionEnded(stopApp)
    })
    
    # Run app in browser
    runApp(list(ui=ui,server=server), launch.browser = TRUE)
    

    这是它运行的屏幕截图:

    【讨论】:

    • 就是这样。非常感谢您的帮助。问题是我不知道req(input$file)。我想知道阻止反应被触发的方法是什么,就是这样!将对我未来的 Shiny 编程非常有帮助。科学记数法很奇怪,即使我使用options() 将其关闭,我也遇到了问题,所以我只是将其注释掉。但是这个解决方案是理想的!
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多