Ошибка в данных с реактивной неверной (NULL) левой стороны присвоения - PullRequest
0 голосов
/ 02 ноября 2018

Я новичок в Shiny (и несколько новичок в R) и пытаюсь создать свое первое пригодное для использования приложение (я создал несколько практических приложений).

Я пытаюсь

  1. Разрешить пользователю выбрать входной файл, затем
  2. Создание временной шкалы проекта (диаграммы Ганта) на основе этого входного файла.

Я нашел некоторые ошибки, которые не понимаю, Error in data()$Start <- reactive({ : invalid (NULL) left side of assignment

Из того, что я понимаю, мне нужно сделать что-то реактивное, хотя я не уверен, что это такое. Чего мне не хватает?

Вот имена столбцов для моего входного файла:

colnames(file1)<-c("Eventdescription", "Start", "End", "Group")

С текстом, датой, датой и текстом в каждом столбце соответственно.

И мой код:

  library(shiny)
  library(plotly)
  library(tidyverse)

  ui<-fluidPage(
    fluidRow(# App title ----
    titlePanel("Upload a File to update the Project Timeline"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

  # Sidebar panel for inputs ----
  sidebarPanel(

  # Input: Select a file ----
  fileInput("file1", "Choose the updated CSV File",
            multiple = FALSE,
            accept = c("text/csv",
                       "text/comma-separated-values,text/plain",
                       ".csv")),
  # Horizontal line ----
  tags$hr(),
  # Input: Checkbox if file has header ----
  checkboxInput("header", "Header", TRUE),
  # Input: Select separator ----
  radioButtons("sep", "Separator",
               choices = c(Comma = ",",
                           Semicolon = ";",
                           Tab = "\t"),
               selected = ","),
  # Input: Select quotes ----
  radioButtons("quote", "Quote",
               choices = c(None = "",
                           "Double Quote" = '"',
                           "Single Quote" = "'"),
               selected = '"'),

  tags$hr(),

  # Input: Select number of rows to display ----
  radioButtons("disp", "Display",
               choices = c(Head = "head",
                           All = "all"),
               selected = "head")
  ),
  # Main panel for displaying outputs ----
  mainPanel(
  # Output: Data file ----
  tableOutput("contents")
  )
  )
  ),

  fluidRow(column(3,actionButton(inputId='go', label = 'Update project       timeline')),
 #using this action button to trigger an update in the graph once the   user clicks on the button rather than a near instantaneous change
 column(9, plotOutput("plot"))
 )

 )

 server<-function(input, output) {

 output$contents <- renderTable({
 # input$file1 will be NULL initially.
 req(input$file1)
 # when reading semicolon separated files,
 # having a comma separator causes `read.csv` to error
 tryCatch(
  {
    df <- read.csv(input$file1$datapath,
                   header = input$header,
                   sep = input$sep,
                   quote = input$quote)
  },
  error = function(e) {
    # return a safeError if a parsing error occurs
    stop(safeError(e))
  }
  )
   if(input$disp == "head") {
    return(head(df))
  }
   else {
  return(df)
  }
  })

  data<- eventReactive(input$go,{input$file1})

  data()$Start<-reactive({strptime(data()$Start, format="%m/%d/%Y")}) 
  data()$End<-reactive({strptime(data()$End, format="%m/%d/%Y")})

  data()$Start<-reactive({as.Date(data()$Start, format="%m%d%Y")}) 
  data()$End<-reactive({as.Date(data()$End, format="%m%d%Y")})

  cols <-reactive({RColorBrewer::brewer.pal(length(unique(data()$Group)), name = "Set2")})    
  data()$color <- reactive({factor(data()$Group, labels = cols())})  

  pl_ot<-reactive({plot_ly()})

  data()$Duration<-reactive({ifelse(is.na(data()$End), 0, data()$End-   data()$Start)})

  for(i in (1:nrow(data()))){
  pl_ot() <- reactive({add_trace(pl_ot(),
                 x = c(data()$Start[i], data()$Start[i] +    data()$Duration[i]),  # x0, x1
               y = c(i, i),  # y0, y1   
             mode = "lines",
             line = list(color = data()$color[i], width = 10),#adjusting the width allows for 'white' space
             showlegend = F,
             hoverinfo = "text",
       #Create custom hover text
          text=paste("Task: ", data()$Eventdescription[i], "<br>",
                     "Duration: ", data()$Duration[i], "days<br>",
                    "Goal: ", data()$Group[i]),
        evaluate=T 
     )})
     }

   #Add information to the and make it more presentable

   pl_ot()<-layout(pl_ot(), 
   #Axis options: 1. Remove gridlines 2. Customize y-axis tick labels
           xaxis= list(showgrid=F,showline=FALSE,   tickfont=list(color="black"), xaxis=list(title=""), side='top', line='top'),
          yaxis=list(showgrid=F, tickfont=list(color="#black"),  title="Project Activities",
                    tickmode="array", showticklabels=FALSE, tickvals=1:nrow(data()),domain=c(0,2.0), margin=list(l=2000)),
       title=list(title="IHTC Project Timeline"),
      pl_ot()
      )

      output$plot<-renderPlot({pl_ot()}) 

      }

      shinyApp(ui=ui, server=server)
...