Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - A shiny app that appends numbers to a 1D vector

I would like this app to add whatever number is selected (above zero) in the numeric input to a 1d vector every time that the button is pressed. It should then present that vector as a list of numbers in a box.

library(shiny)
options(shiny.autoreload = TRUE)

ui <- dashboardPage(
    dashboardHeader(title = "minrep"),
    dashboardSidebar(
        numericInput("number",
                     label = "Enter a number",
                     value = 0,
                     min = 1,
                     max = 100000),
        actionButton(
            "add.number",
            label = "add a number"
        ),
        box(
            title = "List of numbers",
            span(
                textOutput("numbers"),
                style = "color:black"
            )
        )
    ),
    dashboardBody()
)

server <- function(input, output, session) {
    
    list_numbers <- c()
    new_number <- 
        eventReactive(input$add.number, {
            input$number
        })
    observeEvent(input$add.number,{
        list_numbers <- append(list_numbers, new_number())
    })
    output$numbers <- renderText(
        list_numbers
    )
}

shinyApp(ui, server)
question from:https://stackoverflow.com/questions/65888857/a-shiny-app-that-appends-numbers-to-a-1d-vector

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

1 Reply

0 votes
by (71.8m points)

Sure, the trick will be to store our vector as a reactiveValue, so we can access it and change it from wherever we want.

library(shiny)

ui <- fluidPage(

    numericInput("number", label = "Enter a number", value = 1, min = 1, max = 100000),

    actionButton("add.number", label = "add a number"),

    textOutput("numbers")

)

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

    #Reactive value to store our vector
    reactives <- reactiveValues(
        list_numbers = c()
    )

    #Button is pressed
    observeEvent(input$add.number, {
        reactives$list_numbers <- append(reactives$list_numbers, input$number)
    })

    #Textbox Output
    output$numbers <- renderText(
        reactives$list_numbers
    )

}

shinyApp(ui, server)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...