Удаление строки из data.frame (R блестящий) - PullRequest
0 голосов
/ 12 февраля 2019

Я пытаюсь запрограммировать блестящее приложение, которое читает ваш файл * .csv и создает график из этого файла.Файл имеет заголовок и дно, содержащие несколько строк, которые пользователь должен иметь возможность удалить в блестящем приложении.Так что в основном этот отредактированный файл является источником для графика.

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

  if (!require("shiny")) install.packages("shiny", dependencies = TRUE) 
  if (!require("shinyjs")) install.packages("shinyjs", dependencies = TRUE) 
  if (!require("DT")) install.packages("DT", dependencies = TRUE)   

  library(shiny)
  library(shinyjs)
  library(DT)

  ui <- fluidPage(
    tabsetPanel(  
      tabPanel("Upload File",
        titlePanel("Uploading Files"),
          sidebarLayout(
            sidebarPanel(
              fileInput('file1', 'Choose CSV File', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
              tags$br(),
              checkboxInput('header', 'Header', FALSE),
              radioButtons('sep', 'Separator', c(Semicolon=';', Comma=',', Tab='\t'), ','),
                   radioButtons('quote', 'Quote',c(None='', 'Double Quote'='"', 'Single Quote'="'"), '"'),
                   actionButton('delete_row', 'Delete row')
              ),
             mainPanel(
                   DT::dataTableOutput('contents')
             )
          )
       ),

       tabPanel("Plot",
         pageWithSidebar(
            headerPanel('Visualisation'),
              sidebarPanel(
                selectInput('xcol', 'X Variable', ""),
                selectInput('ycol', 'Y Variable', "", selected = ""),
                textOutput("m_out")
              ),
              mainPanel(
                plotOutput('MyPlot')
              )
          )
       )
    )
  )

  server <- function(input, output, session) {

    data <- reactive({ 
      req(input$file1) 
      inFile <- input$file1 
      df <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote)
      updateSelectInput(session, inputId = 'xcol', label = 'X Variable', choices = names(df), selected = names(df))
      updateSelectInput(session, inputId = 'ycol', label = 'Y Variable', choices = names(df), selected = names(df)[2])
      return(df)
    })

    ### This part is the problem
    ###
    observeEvent(input$delete_row, {
      if (!is.null(input$contents_rows_selected)) {
        #print(input$contents_rows_selected) #testing input
        data$values <- data$values[-nrow(input$contents_rows_selected),]

      }
    })
    ###
    ### End of problem

    output$contents = DT::renderDataTable({
      data()
    })

    output$MyPlot <- renderPlot({
      x <- data()[, c(input$xcol, input$ycol)]
      plot(x)
    })

  }

  ### End of server commands

  ### Start Shiny App
  shinyApp(ui = ui, server = server)

Заранее спасибо за помощь.Проблема помечена ###

1 Ответ

0 голосов
/ 12 февраля 2019

Попробуйте превратить переменную данных в реактив ().Я бы предложил также ввести ваш входной файл $ file1, который считывает фрейм данных.В функции сервера:

  data <- reactiveVal(NULL)

и для установки его значения в событие, наблюдающее отправку входного файла:

observeEvent(input$file1, {
  df <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote)
      updateSelectInput(session, inputId = 'xcol', label = 'X Variable', choices = names(df), selected = names(df))
      updateSelectInput(session, inputId = 'ycol', label = 'Y Variable', choices = names(df), selected = names(df)[2])
      data(df)
})

Удаление строки в таком случае будет выглядеть примерно так:

...
df2 <- data()
df2 <- df2[-nrow(input$contents_rows_selected),]
data(df2)
...

Это позволит другим функциям пользовательского интерфейса запускаться при наблюдении за изменениями в (реактивном) объекте data ().

...