Ошибка блестящего приложения в ObserveEvent? Ошибка в [.default: неверный тип индекса 'list' - PullRequest
1 голос
/ 22 мая 2019

Я пишу блестящее приложение, часть которого включает в себя ввод текста пользователем для имитации кода R и само приложение, выбирающее определенные слова из этого ввода для печати вектора, связанного с тем, что вызывает пользователь. Однако, когда я пытаюсь ввести какие-либо слова в приложение и нажать кнопку действия, это приведет к сбою программы и вернет ошибку: Предупреждение: Ошибка в [.default: недопустимый тип индекса «list» с указанием того, что он находится в обработчик наблюдающего события. В событии есть список, но в какой-то момент я удалю его из списка, так как не могу работать с ним так, как планировал иначе, и я не уверен, как это мешает работе приложения или вызывает его сбой. Я предоставил соответствующую часть кода приложения ниже:

 library(shiny)
 library(stringr)

 site <- c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5))
 my.num <- 1:20
 temp <- rnorm(20, 5, 1)
 growth <- 5*temp + rnorm(20, 0, 2)

  my.data <- data.frame(site = site, my.num = my.num, temp = temp, growth = growth)

 ui <- pageWithSidebar(
     headerPanel('Data Wrangler'), 
        sidebarPanel(
       p("It is important to use the right commands to be able to properly format
           your data. Let's see what it looks like when we try to use the combine function (c) tp join our variables
            instead, for instance:"),
   textInput("var.com", "Combine several of the variables using c():", NULL),
    actionButton("go6", "GO!")
   ), 
  mainPanel(
    textOutput("display2")
  ))

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

 buttonValue <- reactiveValues(go6=FALSE)

   observeEvent(input$go6, {

     isolate({
       buttonValue$go6 = TRUE
     })

     games <- names(my.data)
     tofind <- paste(games, collapse="|")

     cominput <- str_extract_all(input$var.com, tofind)

     printables <- NULL


    for (i in 1:length(cominput)){


       printables[i] <- c(my.data[cominput[i]])
       printables

     }

     working <- unlist(printables)




      output$display2 <- renderText(
      is.not.null <- function(x) !is.null(x),

      if (is.not.null(working)) {
        print(working)
      } else {
        print("Sorry, this is incorrect; check your signage.")
      }
    )





    session$onSessionEnded({
     stopApp
   }) 

 })
 }

 shinyApp(ui = ui, server = server)

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

Редактировать: ниже я включил скриншот некоторых ожидаемых результатов, используя код перед передачей в Shiny. Он должен иметь возможность взять любое из имен переменных («site», «temp», «growth») и т. Д., Объединить их вместе и вывести их в виде длинного вектора, чтобы смоделировать, что произойдет, если вы просто попытаетесь объединить их с помощью c (). Демо-код для этого вывода выглядит следующим образом:

   library(stringr)

   site <- c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5))
   my.num <- 1:20
   temp <- rnorm(20, 5, 1)
   growth <- 5*temp + rnorm(20, 0, 2)

   my.data <- data.frame(site = site, my.num = my.num, temp = temp, growth = growth)

dubbo <- c("temp", "my.num")
 games <- names(my.data)

   tofind <- paste(games, collapse="|")

    secondinput <- str_extract_all(dubbo, tofind)
    printables <- NULL


   for (i in 1:length(secondinput)){


     printables[i] <- c(my.data[secondinput[[i]]])
     printables

    }

  susus <- NULL

   susus <- unlist(printables)
    susus

Ожидаемый результат: enter image description here

1 Ответ

1 голос
/ 23 мая 2019

Вам не хватает обработки некоторых ошибок после str_extract_all, и вы пытаетесь получить доступ к элементам cominput (что является list()) неправильным способом.

Делает ли это то, что вы ожидаете?:

library(shiny)
library(stringr)

site <- c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5))
my.num <- 1:20
temp <- rnorm(20, 5, 1)
growth <- 5 * temp + rnorm(20, 0, 2)

my.data <-
  data.frame(
    site = site,
    my.num = my.num,
    temp = temp,
    growth = growth
  )

ui <- pageWithSidebar(
  headerPanel('Data Wrangler'),
  sidebarPanel(
    p(
      "It is important to use the right commands to be able to properly format
           your data. Let's see what it looks like when we try to use the combine function (c) tp join our variables
            instead, for instance:"
    ),
    textInput("var.com", "Combine several of the variables using c():", NULL),
    actionButton("go6", "GO!")
  ),
  mainPanel(textOutput("display2"))
)

server <- function(input, output, session) {
  buttonValue <- reactiveValues(go6 = FALSE)

  observeEvent(input$go6, {
    isolate({
      buttonValue$go6 = TRUE
    })

    games <- names(my.data)
    tofind <- paste(games, collapse = "|")

    cominput <- str_extract_all(input$var.com, tofind)

    printables <- list(NULL)

    if (identical(cominput, list(character(0)))) {
      working <- NULL
    } else {
      for (i in 1:length(unlist(cominput))) {
        printables[i] <- c(my.data[cominput[[1]][i]])
      }
      working <- unlist(printables)
    }

    output$display2 <- renderText(if (!is.null(working)) {
      print(working)
    } else {
      print("Sorry, this is incorrect; check your signage.")
    })

    session$onSessionEnded({
      stopApp
    })

  })
}

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