Неверная (NULL) левая сторона ошибки присваивания в Shiny - PullRequest
0 голосов
/ 29 апреля 2019

Я знаю, что этот вопрос был опубликован несколько раз, но я впервые развиваю что-то, что я блестяю, и меня смущает пара разных вещей. Одним из них является правильный ввод фрейма данных и использование его в функциях вывода.

Мои единственные цели прямо сейчас:

  1. Отображение заголовка или полного кадра данных в зависимости от выбора пользователя

  2. У меня есть двоичный столбец с именем status (статус «Пройден» или «Не пройден»). Я хочу сгруппировать по датам, чтобы посчитать статус (любой бы сделал) и построить его.

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(readxl)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Data Quality Result Monitoring"),

   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
        fileInput('file1', 'Choose xlsx file',
                  accept = c(".xlsx")
        ),

        sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

        radioButtons("disp", "Display",
                choices = c(Head = "head",
                            All = "all"),
                selected = "head")

      ),
      # Show a plot of the generated distribution
      mainPanel(
         #plotOutput("linechart"),

         h4("Observations"),
         tableOutput("contents")
      )
)    


# Define server logic required to draw a histogram'
library(ggplot2)
server <- function(input, output) {

   df <- reactive({

     inFile <- input$file1

     if (is.null(inFile))
     return(NULL)

     df <- read_xlsx(inFile$datapath, sheet =  1)

    return(inFile)})

  output$linechart <- renderPlot({
   ndf() <- group_by(df,Execution_Date) %>% summarize( count = n() )

   ggplot(ndf()) + geom_bar(aes(x=week,y=count),stat="identity")
   })

   output$contents <- renderTable({

     # input$file1 will be NULL initially. After the user selects
     # and uploads a file, head of that data file by default,
     # or all rows if selected, will be shown.

     dataset() <- df
     if(input$disp == "head") {
       return(head(dataset()))
     }
     else {
       return(dataset())
     }

   })

}

# Run the application 
shinyApp(ui = ui, server = server)

Ответы [ 2 ]

0 голосов
/ 29 апреля 2019
dataset() <- df

Здесь вы получите ошибку:

 "Error in <-: invalid (NULL) left side of assignment"

Вы не можете присвоить значение реактивному выражению. Работает наоборот:

dataset <- df()

Поиграйте с этим с помощью функции print.

Другая ошибка в вашем коде:

 df <- read_xlsx(inFile$datapath, sheet =  1)

return(inFile)

Вы возвращаете не ту переменную, вы хотите вернуть df.

Вот код, который должен работать для вас:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(readxl)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Data Quality Result Monitoring"),

  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose xlsx file',
                accept = c(".xlsx")
      ),

      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),

    radioButtons("disp", "Display",
                 choices = c(Head = "head",
                             All = "all"),
                 selected = "head")

  ),
  # Show a plot of the generated distribution
  mainPanel(
    #plotOutput("linechart"),

    h4("Observations"),
    tableOutput("contents")
  )
)    


# Define server logic required to draw a histogram'
library(ggplot2)
server <- function(input, output) {

  df <- reactive({

    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    df <- read_xlsx(inFile$datapath, sheet =  1)

    df

    })

  output$linechart <- renderPlot({
    ndf <- group_by(df(),Execution_Date) %>% summarize( count = n() )

    ggplot(ndf + geom_bar(aes(x=week,y=count),stat="identity"))
  })

  output$contents <- renderTable({

    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.

    dataset <- df()
    if(input$disp == "head") {
      return(head(dataset))
    }
    else {
      return(dataset)
    }

  })

}

# Run the application 
shinyApp(ui = ui, server = server)

Я также рекомендую вам реализовать проверку структуры и имен в вашем коде.

0 голосов
/ 29 апреля 2019

Это связано с ndf() <- group_by(df,Execution_Date) %>% summarize( count = n() )

ndf() - это пустая функция, которая не существует.

df является реактивным, и вы используете его с df() вместо df, что означает, что код оценивается при каждом изменении реактивности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...