【发布时间】:2019-05-19 16:47:30
【问题描述】:
我的问题比the question here 更高级一点。假设我想将以下游戏开发为 Shiny 应用程序。
我有 3 x 3 的数据框,其中包含从 1 到 9 的随机数字。
set.seed(123)
df_correct <- as.data.frame(matrix(sample(9), nrow = 3, ncol = 3))
df_correct
V1 V2 V3
1 3 6 2
2 7 5 8
3 9 1 4
当 Shiny 应用加载时,用户会看到一个空的 3 x 3 rhandsontable 以及一个提交按钮。游戏的目标是成功找到“隐藏在每个单元格后面”的数字。
我试图实现的是在单击提交按钮时根据用户输入对单元格进行动态颜色编码(红色 = 错误,绿色 = 正确,浅灰色 = 空)。尽管我不知道如何用 Javascript 编码,但this tutorial on the rhandsontable package 提供了代码示例,这些示例相对容易理解和调整。我分三个步骤进行:
识别空单元格
识别具有正确用户输入的单元格
识别用户输入错误的单元格
每个步骤都会生成一个包含索引(即行号和列号)的 R 对象。我不知道如何将此信息传递给 hot_cols() 函数(更具体地说,传递给接受 Javascript 代码的 renderer 参数)。非常感谢您的帮助。
library(shiny)
library(rhandsontable)
library(magrittr)
ui <- fluidPage(
titlePanel("Simple game"),
rHandsontableOutput("table"),
actionButton("button", "Submit")
)
server <- function(input, output) {
tables <- reactiveValues(
df_correct = {
set.seed(123)
as.data.frame(matrix(sample(9), nrow = 3, ncol = 3))
},
df_user = rhandsontable(
data = as.data.frame(matrix(NA_integer_, nrow = 3, ncol = 3)
))
)
output$table <- renderRHandsontable({
tables$df_user
})
observeEvent(input$button, {
df <- hot_to_r(input$table)
index_empty <- which(is.na(df), arr.ind = TRUE)
index_correct <- which(df == tables$df_correct, arr.ind = TRUE)
index_wrong <- which(df != tables$df_correct, arr.ind = TRUE)
tables$df_user <-
df %>%
rhandsontable() %>%
hot_cols(renderer = "")
})
}
shinyApp(ui = ui, server = server)
【问题讨论】:
标签: javascript r shiny handsontable rhandsontable