Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

r - Who to write a table using a Shiny input

Hello the following code returns an error and the app crashes. The error refers to "You tried to do something that can only be done from inside a reactive expression or observer".

library(shiny)

ui <- fluidPage(
  theme = "",
  titlePanel(""),
  sidebarPanel(textInput("freetext", "Write Something")),
  mainPanel(textOutput("testtext"))
)


server <- function(input, output) {

  output$testtext <- renderText(paste("I wrote: ", input$freetext))

  table <- data.frame(wrote = input$freetext)
  
  write.csv(table, "~/testtable.csv", row.names = FALSE)

}

shinyApp(ui, server)

I have tried to add the input$freetext into a reactive element but with no luck.

server <- function(input, output) {

  output$testtext <- renderText(paste("I wrote: ", input$freetext))

  outtext <- reactive({input$freetext})

  table <- data.frame(wrote = outtext())

  write.csv(table, "~/testtable.csv", row.names = FALSE)

}

How can I add the value from input$freetext to the data.frame?

Answer: This worked

library(shiny)

ui <- fluidPage(
  theme = "",
  titlePanel(""),
  sidebarPanel(textInput("freetext", "Write Something")),
  mainPanel(textOutput("testtext"))
)


server <- function(input, output) {

  output$testtext <- renderText(paste("I wrote: ", input$freetext))

  observeEvent(input$freetext, {
    if(nchar(input$freetext) > 0) {
      t <-input$freetext
      table <- data.frame(wrote = t)

      write.csv(table, "/shiny-data/users/scotcan1/testApp/testtable.csv", row.names = FALSE)
      }
  })



}

shinyApp(ui, server)

question from:https://stackoverflow.com/questions/65940372/who-to-write-a-table-using-a-shiny-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found this to work.

library(shiny)

ui <- fluidPage(
  theme = "",
  titlePanel(""),
  sidebarPanel(textInput("freetext", "Write Something")),
  mainPanel(textOutput("testtext"))
)


server <- function(input, output) {

  output$testtext <- renderText(paste("I wrote: ", input$freetext))

  observeEvent(input$freetext, {
    if(nchar(input$freetext) > 0) {
      t <-input$freetext
      table <- data.frame(wrote = t)

      write.csv(table, "/shiny-data/users/scotcan1/testApp/testtable.csv", row.names = FALSE)
      }
  })



}

shinyApp(ui, server)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...