2017-02-15 1 views
2

Я пытаюсь создать блестящее приложение, подобное тому, где после выбора входных данных я могу щелкнуть по «отправке» botton, который автоматически загружает cvs файл, добавляющий строку с новыми данными. я вижу, что структура должна быть похожа на обследование одного, это мой код, он дает следующее сообщение об ошибке:Сохраните введенное значение в файле cvs, добавив строку при каждом представлении, в блестящем

Listening on http://127.0.0.1:3716 
Warning: Error in <-: invalid type/length (closure/0) in vector allocation 
Stack trace (innermost first): 
42: server [/Users/cleliagasparri/app2/app.R#47] 
1: runApp 
Error in Data[nrow(Data) + 1, ] <- reactive(if (input$Action == 1) { : 
invalid type/length (closure/0) in vector allocation 

Код:

library(shiny) 
library(googlesheets) 
library(DT) 


# Define UI for application that draws a histogram 
library(shiny) 
ui <- fluidPage(
textInput("nome", "Nome"), 

textInput("cognome", "Cognome"), 

textInput("email", "Email"), 

radioButtons("gioiello", label = "Gioiello", choices = c("Orecchini" = 1, "Collana" = 2) 
), 

conditionalPanel(condition = "input.gioiello == 1", 
selectInput(inputId = "modello",     
      label = "Modello",         
      choices = c("Serpenti" = 1, "Foglie" = 2, "Edere" = 3,    # Responses 
          "Neither Agree nor Disagree" = 4, "Agree Somewhat" = 5, "Agree" = 6, 
          "Agree Strongly" = 7)    
)), 
    conditionalPanel(condition = "input.gioiello == 2", 
       selectInput(inputId = "modello",     #  What we are calling the object 
           label = "Modello",         # Label 
          choices = c("Serpenti" = 1, "Foglie" = 2, "Edere" = 3,  # Responses 
             "Neither Agree nor Disagree" = 4, "Agree Somewhat" = 5, "Agree" = 6, 
             "Agree Strongly" = 7)    
       )), 
radioButtons("materiale", label = "Materiale", choices = c("Oro",  "Argento", "Bronzo rosa", "Bronzo giallo", "Rame") 
      ), 

    actionButton("Action", "Submit"), tags$hr() 


) 

library(shiny) 
library("DT")                        

server <- function(input, output){ 
Results <- reactive(c(nome, cognome, email, gioiello, modello,  materiale, Sys.Date())) 

Data[nrow(Data) +1,] <- reactive( if(input$Action == 1) {Results()})  # Put data into next row of the "Data" when the action button is pressed 
    write.csv(Data, file = "/Users/cleliagasparri/app2/Data.csv")    # Download new Data to replace Data.csv file in the shiny folder 


#####  Function 1, Create a data download option #### 

output$downloadData <- downloadHandler(   # Create the download file name 
    filename = function() { 
    paste("data-", Sys.Date(), ".csv", sep="") 
}, 
content = function(file) { 
    write.csv(Data, file)      # put Data() into the download file 
})       

}                     

shinyApp(ui = ui, server = server) 
+0

Не могли бы вы предоставить образцы данных? Также библиотека не должна находиться внутри '' ''. Он должен быть 'library (DT)' вместо 'library (" DT ")' – SBista

+0

Спасибо! Я хочу использовать это приложение, чтобы вставлять данные о продаже драгоценностей, поэтому после того, как вы вставляете проданную часть, я нажимаю кнопку «отправить», которая добавляет строку с данными о продажах в файл csv. Строка должна быть заполнена таким образом: имя, фамилия, адрес электронной почты, тип драгоценности (серьга, ожерелье, браслет ..), модель (различная для каждого типа), материал (золото, серебро, бронза), цена, sysdate – Clelia

ответ

1

Это может не быть лучшим способом сделать но он выполняет эту работу.

Я добавил еще одну кнопку для загрузки, так что она работает с обработчиком загрузки. Чтобы сделать то, что я делаю более ясно, я добавил вывод таблицы. Кнопка submit теперь добавляет строку в таблицу, которая внутренне сохраняется как фрейм данных. Можно сохранить кнопку загрузки файла.

library(shiny) 
ui <- fluidPage(
    textInput("nome", "Nome"), 

    textInput("cognome", "Cognome"), 

    textInput("email", "Email"), 

    radioButtons("gioiello", label = "Gioiello", choices = c("Orecchini" = 1, "Collana" = 2) 
), 

    conditionalPanel(condition = "input.gioiello == 1", 
        selectInput(inputId = "modello",     
           label = "Modello",         
           choices = c("Serpenti" = 1, "Foglie" = 2, "Edere" = 3,    # Responses 
              "Neither Agree nor Disagree" = 4, "Agree Somewhat" = 5, "Agree" = 6, 
              "Agree Strongly" = 7)    
        )), 
    conditionalPanel(condition = "input.gioiello == 2", 
        selectInput(inputId = "modello",     #  What we are calling the object 
           label = "Modello",         # Label 
           choices = c("Serpenti" = 1, "Foglie" = 2, "Edere" = 3,  # Responses 
              "Neither Agree nor Disagree" = 4, "Agree Somewhat" = 5, "Agree" = 6, 
              "Agree Strongly" = 7)    
        )), 
    radioButtons("materiale", label = "Materiale", choices = c("Oro",  "Argento", "Bronzo rosa", "Bronzo giallo", "Rame") 
), 
    #Table showing what is there in the data frame 
    tableOutput("table"), 
    #Button which appends row to the existing dataframe 
    actionButton("Action", "Submit"), 

    #Button to save the file 
    downloadButton('downloadData', 'Download') 


) 

library(shiny) 


server <- function(input, output){ 
    #Global variable to save the data 
    Data <- data.frame() 

    Results <- reactive(data.frame(input$nome, input$cognome, input$email, input$gioiello, input$modello, input$materiale, Sys.Date())) 

    #To append the row and display in the table when the submit button is clicked 
    observeEvent(input$Action,{ 
    #Append the row in the dataframe 
    Data <<- rbind(Data,Results()) 
    #Display the output in the table 
    output$table <- renderTable(Data) 
    }) 



    output$downloadData <- downloadHandler(

# Create the download file name 
    filename = function() { 
     paste("data-", Sys.Date(), ".csv", sep="") 
    }, 
    content = function(file) { 
     write.csv(Data, file)      # put Data() into the download file 
    })       

}                     

shinyApp(ui = ui, server = server) 

Надеюсь, это поможет!

+0

Спасибо ! оно работает! Могу ли я спросить вас, как изменить путь загрузки для сохранения cvs в другом каталоге? – Clelia

+0

Вы всегда можете выбрать путь из появившегося диалогового окна. Вы хотите, чтобы вы сохранили файл в файле по умолчанию без появления диалогового окна файла? – SBista

+0

Если я хорошо понимаю, каждый раз, когда загружается дата-карта, создается csv с строкой, представленной в текущем сеансе. Если я скачал 2 csv в 2 разных днях, оба с тем же именем файла, первый будет перезаписан; это правильно? Спасибо! – Clelia

Смежные вопросы