gpt4 book ai didi

r - 将 json/data 传递给 Shiny 的 javascript 对象

转载 作者:行者123 更新时间:2023-12-02 07:27:16 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何让 R 通过 shiny 与其他 javascript 元素进行交互,我猜这意味着 server.Rui.R 提供自定义 Shiny 对象(最好是 json 格式?) ,然后将其转换为 javascript 数组。我正在进行的工作代码是:

server.R

library(shiny)

shinyServer(
function(input, output) {
output$species_table <- renderTable({ iris[iris$Species == input$species,] })
output$json <- RJSONIO::toJSON(iris[iris$Species == input$species,], byrow=T, colNames=T) # error line
}
)

ui.R

require(shiny)
specs = as.character(unique(iris$Species))
names(specs) = specs

pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
tableOutput("species_table")
)
)

返回服务器错误:

Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside
a reactive expression or observer.)

.. 因为这显然是错误的方法。没有 server.R 的行 output$json <- ...结果有效并且looks like this ,所以其余代码没问题。但我也想以某种方式获取 json(或任何替代格式)并触发后续的 javascript 操作以将其作为数组对象读入。感谢您的指点,如果我的描述不清楚,请提前致歉。

最佳答案

为了他人的利益,这是工作公式。如果有人能提出更优雅的解决方案,我将不胜感激。打开浏览器的 javascript 控制台日志以查看正在更新的对象“数据”。

server.R

library(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))

shinyServer(
function(input, output) {
output$json <- reactive({
paste('<script>data=',
RJSONIO::toJSON(iris[iris$species == input$species,], byrow=T, colNames=T),
';console.log(data[0]);', # print 1 data line to console
'</script>')
})
}
)

ui.R

require(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))
specs <- as.character(unique(iris$species))
names(specs) <- specs

pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
htmlOutput("json")
)
)

关于r - 将 json/data 传递给 Shiny 的 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26719334/

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