gpt4 book ai didi

R - 计算 Shiny 下载按钮的点击次数

转载 作者:行者123 更新时间:2023-12-01 21:38:55 26 4
gpt4 key购买 nike

是否有内置的 Shiny 属性可以计算 downloadButton 被点击的次数?我在功能帮助或网络搜索中没有找到它。如果没有内置方法,我将如何计算点击次数。这是一个有效的示例:

data <- matrix(1:20, nrow=5)
ui <- fluidPage(title = 'Count Button Clicks',
fluidRow(style = "padding-bottom: 20px;",
column(width=6,
textOutput("actionclickCount"),
br(),
textOutput("downloadclickCount")
),
column(width=6,
actionButton("actionBtn", "Action Button"),
br(),
downloadButton("dwnldBtn", "Download Button")
)
)
)

server <- function(input, output, session) {
output$actionclickCount <- renderText({
paste('Action Button Clicks =',input$actionBtn)
})

output$downloadclickCount <- renderText({
paste('Download Button Clicks =','what variable goes here?')
})

output$dwnldBtn <- downloadHandler(
filename = 'data.csv',
content = function(file){
write.csv(data, file)
},
contentType = 'csv'
)
}

shinyApp(ui = ui, server = server)

最佳答案

我认为没有内置方法。但您可以自己构建它。

您可以通过使用 javascript 向按钮添加点击监听器来完成此操作:

  observe({
if(is.null(input$rnd)){
runjs("
var click = 0;
Shiny.onInputChange('rnd', click)
var dwnldBtn = document.getElementById('dwnldBtn')
dwnldBtn.onclick = function() {click += 1; Shiny.onInputChange('rnd', click)};
")
}
})

来自 Shiny.onInputChange('rnd', click) 的输出可以通过 input$rnd 在 Shiny 中访问。

编辑:对于多个按钮,您可以使用:

  observe({
for(btn1 in 1:2){
if(is.null(input[[paste0("rnd", btn1)]])){
runjs(
paste0("
var counter", btn1 ,"= 0;
var dwnldBtn = document.getElementById('", paste0("dwnldBtn", btn1), "')
dwnldBtn.onclick = function() {counter", btn1, " +=1; Shiny.onInputChange('", paste0("rnd", btn1), "', counter", btn1,")};
")
)
}
}
})

有关工作示例,请参见下文:

   library(shiny)
library(shinyjs)
data <- matrix(1:20, nrow=5)

ui <- fluidPage(title = 'Count Button Clicks',
useShinyjs(),
fluidRow(style = "padding-bottom: 20px;",
column(width=6,
textOutput("actionclickCount"),
br(),
textOutput("downloadclickCount")
),
column(width=6,
actionButton("actionBtn", "Action Button"),
br(),
downloadButton("dwnldBtn", "Download Button")
)
)
)

server <- function(input, output, session) {
output$actionclickCount <- renderText({
paste('Action Button Clicks =',input$actionBtn)
})

output$downloadclickCount <- renderText({
paste('Download Button Clicks =', input$rnd)
})

output$dwnldBtn <- downloadHandler(
filename = 'data.csv',
content = function(file){
write.csv(data, file)
},
contentType = 'csv'
)

observe({
if(is.null(input$rnd)){
runjs("
var click = 0;
Shiny.onInputChange('rnd', click)
var dwnldBtn = document.getElementById('dwnldBtn')
dwnldBtn.onclick = function() {click += 1; Shiny.onInputChange('rnd', click)};
")
}
})

}

runApp(shinyApp(ui = ui, server = server), launch.browser = TRUE)

关于R - 计算 Shiny 下载按钮的点击次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com