Skip to content

Instantly share code, notes, and snippets.

@SachaEpskamp
Last active November 16, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SachaEpskamp/ba61375b832b02861e9c0702af1f4a67 to your computer and use it in GitHub Desktop.
Save SachaEpskamp/ba61375b832b02861e9c0702af1f4a67 to your computer and use it in GitHub Desktop.
library(shiny)
ui <- fluidPage(
h4("Click on plot to start drawing, click again to pause. Draw from LEFT to RIGHT"),
# sliderInput("mywidth", "width of the pencil", min=1, max=30, step=1, value=10),
plotOutput("plot", width = "800px", height = "500px",
hover=hoverOpts(id = "hover", delay = 100, delayType = "throttle", clip = TRUE, nullOutside = TRUE),
click="click"),
actionButton("reset", "RESET DRAWING"),
textInput("userid","Write your participant ID"),
downloadButton("downloadData", "Download data"))
server <- function(input, output, session) {
vals = reactiveValues(x=NULL, y=NULL)
draw = reactiveVal(FALSE)
observeEvent(input$click, handlerExpr = {
temp <- draw(); draw(!temp)
if(!draw()) {
vals$x <- c(vals$x, NA)
vals$y <- c(vals$y, NA)
}})
observeEvent(input$reset, handlerExpr = {
vals$x <- NULL; vals$y <- NULL
})
observeEvent(input$hover, {
if (draw()) {
vals$x <- c(vals$x, round(input$hover$x))
vals$y <- c(vals$y, round(input$hover$y))
if (length(vals$x) > 1){
if (vals$x[length(vals$x)] < max(vals$x)){
vals$y <- vals$y[vals$x<=vals$x[length(vals$x)]]
vals$x <- vals$x[vals$x<=vals$x[length(vals$x)]]
}
vals$y <- rev(rev(vals$y)[!duplicated(rev(vals$x))])
vals$x <- rev(rev(vals$x)[!duplicated(rev(vals$x))])
}
}})
output$plot= renderPlot({
plot(x=vals$x, y=vals$y, xlim=c(0, 100), ylim=c(0, 100), ylab="Amount", xlab="Year", type="l", lwd=2, xaxt="n")
axis(1, at = seq(0,100,by=5), las=2)
})
output$downloadData <- downloadHandler(
filename = function() {
paste0("data-",input$userid, format(Sys.time(), format = "%Y-%m-%d--%H-%M-%S"), ".csv", sep="")
},
content = function(file) {
# Make data frame:
df <- expand.grid(
id = input$userid,
time = Sys.time(),
x = 0:100,
y = NA
)
y <- vals$y[match(df$x,vals$x)]
df$y <- round(approx(df$x[!is.na(y)],y[!is.na(y)],xout=df$x)$y,2)
write.csv(df, file)
}
)
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment