R Shiny key input binding
You can add a listener for keypresses. The Shiny.onInputChange
can be used to bind the key pressed to a shiny variable:
library(shiny)
runApp( list(ui = bootstrapPage(
verbatimTextOutput("results"),
tags$script('
$(document).on("keypress", function (e) {
Shiny.onInputChange("mydata", e.which);
});
')
)
, server = function(input, output, session) {
output$results = renderPrint({
input$mydata
})
}
))
for keydown
events you can substitute:
tags$script('
$(document).on("keydown", function (e) {
Shiny.onInputChange("mydata", e.which);
});
')
R Shiny key and actionButton binding to reactive values
The problem is that the input event only captures the keycode of the pressed key, which stays the same once the key is pressed. Shiny however only reacts if the event data changes. You need to set the event data to something new every time; e.g. the current time stamp. Look at this working example:
library(shiny)
shinyApp(ui <- pageWithSidebar(
headerPanel("Test keyboard control"),
sidebarPanel(
tags$script('$(document).on("keydown",
function (e) {
if(e.which == 68) {
Shiny.onInputChange("downButton", new Date());
} else if (e.which == 85) {
Shiny.onInputChange("upButton", new Date());
}
});
'),
actionButton("downButton", "Down"),
actionButton("upButton", "Up")
),
mainPanel(htmlOutput("text"))
),
server <- function(session, input, output) {
vals <- reactiveValues(count = 0)
observeEvent(input$downButton, {vals$count <- vals$count - 1})
observeEvent(input$upButton, {vals$count <- vals$count + 1})
output$text <- renderText(paste("Counter is:", vals$count))
}
)
Shiny: How to hide and show elements based on keypress / key. input
Try this, I added the keys (e
,i
, SHIFT+e
, SHIFT+i
)
library(shiny)
library(ggplot2)
ui <- fluidPage(
useShinyjs(),
div(
id = "welcome",
mainPanel(
fluidRow(
h3("Welcome"),
p("Welcome to the test."),
br(),
actionButton("continue1", label = "weiter")
)
)
),
hidden(
div(
id = "instruction",
mainPanel(
fluidRow(
h3("Instruction"),
p("Please ...")),
br(),
actionButton("continue2", label = "weiter"))
)
),
hidden(
div(
id = "IAT1",
mainPanel(
fluidRow(
h3("IAT"),
p("IAT word 1")),
br(),
tags$script('$(document).on("keypress", function(e) {
Shiny.onInputChange("keyid1", e.keyCode);
});'))
))
)
server <- function(input, output,session) {
observeEvent(input$continue1, {
show("instruction")
hide("welcome")
})
observeEvent(input$continue2, {
show("IAT1")
hide("instruction")
})
observeEvent(input$keyid1,{
print(input$keyid1)
if(input$keyid1 %in% c(101,105,69,73)) {
hide("IAT1")
show("welcome")
}
else {}
})
}
shinyApp(ui = ui, server = server)
Shiny Responds to Enter
In your case, the problem is reactive programming and this is the reason that you need something to manage this situation. My recommendation is to use observer pattern or validate function.
Observer pattern: shiny implements the observer pattern which is
useful to act when an event happens in an object (it can be a click
in a button, new value in an input...).Validate function: the functionality of this process is similar to an
if/else statement. Indeed, there is need what is the if to check the
parameter, if the values are wrong, there will be an error message.
To know how to use observe pattern and the validate function, click on the previous link (in the Shiny website is everything explained).
R shiny addition of points according to input
Try this short and tidy server expression:
library (shiny)
library(shinyWidgets)
library(fresh)
library(htmltools)
ui<-navbarPage("Addition of points",
tabPanel("Calculation",
fluidPage(
headerPanel(h4("Scores")),
headerPanel(h5("Please select your inputs.")),
fluidRow(
(column (3,
headerPanel(h5(strong("Score1"))),
sliderInput("score1", label = h6("Score1 (1-3), input <=2 should add 6 points to the total score, input >2 should add no points"), min = 1, max = 3, value = 1, ticks = TRUE, animate=TRUE, step = 1, width = "150px")
)),
(column (3,
headerPanel(h5(strong("Score2"))),
numericInput("score2", label = h6("Score2, input <=10 should add 5 points to the total score, input >10 should add no points"), value = "1" , width = "150px")
)),
(column (3,
headerPanel(h5(strong("Score3"))),
radioButtons("score3", label = h6("Score3, clicking on 'No' should add 4 points to the total score, clicking on 'Yes' should add no points"), choices = list("No"=1, "Yes"=2), selected = character(0))
)),
(column (2,
wellPanel(
style = "background: white",
headerPanel(h4(strong("Score:"))),
textOutput("multi")
)))
)))
)
server<-function(input, output) {
B <- reactive({
0 +
(if(!is.null(input$score1) && input$score1<=2) 6 else 0) +
(if(!is.null(input$score2) && input$score2<=10) 5 else 0) +
(if(!is.null(input$score3) && input$score3==1) 4 else 0)
})
output$multi <- renderText ({ B() })
}
shinyApp(ui, server)
R shiny: Add Konami Code inside a Shiny App
library(shiny)
runApp( list(ui = bootstrapPage(
verbatimTextOutput("results"),
verbatimTextOutput("allInputs"),
tags$script('
$(document).on("keypress", function (e) {
Shiny.onInputChange("mydata", e.which);
});
')
)
, server = function(input, output, session) {
output$results = renderPrint({
input$mydata
})
keysPressed <- reactiveVal()
observeEvent(input$mydata, {
keysPressed(c(keysPressed(), input$mydata))
})
output$allInputs = renderPrint({
keysPressed()
})
}
))
ismirsehregal who helped me on the code I found
Is there a way in R shiny to concatenate all values taken by an input
My final code merging all hints:
UI.R (inside body)
tags$script('
pressedKeyCount = 0;
$(document).on("keydown", function (e) {
Shiny.onInputChange("pressedKey", pressedKeyCount++);
Shiny.onInputChange("pressedKeyId", e.which);
});'
),
SERVER.R (somewhere)
keysPressed <- reactiveVal()
observeEvent(input$pressedKey, {
keysPressed(c(keysPressed(), input$pressedKeyId))
})
output$secret <- renderUI({
secretCode = keysPressed()
if(length(secretCode)>=10)
secretCode = secretCode[(length(secretCode)-9):length(secretCode)]
trueCode = c(38,38,40,40,37,39,37,39,66,65)
if(isTRUE(all.equal(secretCode,trueCode))){
HTML('<center><img src="4BA140A6A75546D791B01BC0BA9E00A2.png"></center>')
}
})
c(38,38,40,40,37,39,37,39,66,65) corresponds to famous konami code sequential key inputs
Related Topics
Count Number of Zeros Per Row, and Remove Rows with More Than N Zeros
Converting Two Columns of a Data Frame to a Named Vector
Extract Every Nth Element of a Vector
Dplyr - Using Column Names as Function Arguments
Making a Stacked Bar Plot for Multiple Variables - Ggplot2 in R
How to Remove Empty Factors from Ggplot2 Facets
Finding Point of Intersection in R
Ggplot2: Change Order of Display of a Factor Variable on an Axis
Subsetting Data.Table Using Variables with Same Name as Column
Alignment of Numbers on the Individual Bars
How to Make a List of All Dataframes That Are in My Global Environment
Shiny: Differencebetween Observeevent and Eventreactive
How to Detect the Right Encoding for Read.Csv
How to Access the Last Value in a Vector
Explain Ggplot2 Warning: "Removed K Rows Containing Missing Values"