我成功地将Shiny服务器中的变量返回到客户端,并在server.R中使用函数 session $ sendCustomMessage
现在我想在ui.R客户端中使用这个 leftChoices 变量来创建一个widget chooserInput来创建一个[自定义输入控件] [1],但这不起作用[1]:{ {3}}
我试过使用Shiny.chooserInput但是徒劳无功。该脚本无法识别chooserInput,我不知道如何使其工作。一些帮助。感谢
这是ui.R
source("chooser.R")
library(shiny)
shinyUI(fluidPage(sidebarLayout(sidebarPanel(
fileInput("file1", "Choose file to upload",
accept = c('text/csv','.csv')
)
),
mainPanel(
tabPanel("Data",shiny::dataTableOutput("contents")),
tags$script(src = "initcsv.js"),
chooserInput("mychoice", "Available", "Selected ",
colnames(message.leftChoices) , c(), size = 10, multiple = TRUE
)
)
)
)
)
这是ny server.R
library(shiny)
source("chooser.R")
shinyServer(function(input, output, session) {
data <- reactive ({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath)
})
observe({
session$sendCustomMessage(type = "MyDatasetUpdated",
message = list(
leftChoices=colnames(data())
)
)
})
output$contents <- renderDataTable(
data(), options = list(iDisplayLength = 5)
)
})
这是INITCSV.JS
Shiny.addCustomMessageHandler("MyDatasetUpdated",
function(message) {
if (message.leftChoices != null)
//chooserInput("mychoice", "Available", "Selected ",
//c() , c(), size = 10, multiple = TRUE
// ),
alert(JSON.stringify(message.leftChoices));
})
答案 0 :(得分:1)
好吧,你的代码没有返回消息的主要原因是你在server.R文件中分配了leftChoices。假设您在工作目录中有chooser.R文件,下面提供了侧边栏中的小部件,并提供了一个弹出窗口,其中包含当前的左侧选项&#39;。请注意,如果没有加载数据集时没有选择,我已将chooseInput
电话放在renderUI
内。这样,您可以避免因未加载数据集而导致的任何潜在错误。我已在代码中发表评论以澄清。
ui.R
require(shiny)
source("chooser.R")
shinyUI(fluidPage(
sidebarLayout(sidebarPanel(
fileInput("file1", "choose file to upload",
accept = c('text/csv', '.csv')
)
# here is where the widget currently sits
,uiOutput("choices")
),
mainPanel(
tabPanel("Data", dataTableOutput("contents")),
tags$script(src = "initcsv.js")
)
)
)
)
server.R
require(shiny)
shinyServer(function(input, output, session) {
data <- reactive ({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath)
})
# The renderUI call of chooserInput thereby making it dependent
# on a dataset existing
output$choices <- renderUI({
if (is.null(data())){
return(NULL)
}else{
chooserInput("mychooser", "Available", "Selected",
colnames(data()), c(), size = 10, multiple = TRUE
)
}
})
# note the leftChoices assignment. You must refer to
# mychooser$left for the left choices. This identifier is
# defined in the chooser.R file
observe({
session$sendCustomMessage(type = "MyDatasetUpdated",
message = list(
leftChoices=input$mychooser$left
)
)
})
output$contents <- renderDataTable(
data(), options = list(iDisplayLength = 5)
)
}
)
INITCSV.js - 我只是稍微修改了您的alert
语句以使其更具体(因为在这种情况下您只显示左侧选项。
Shiny.addCustomMessageHandler("MyDatasetUpdated",
function(message) {
if (message.leftChoices != null)
//chooserInput("mychoice", "Available", "Selected ",
//c() , c(), size = 10, multiple = TRUE
// ),
alert("Left Choices: " + JSON.stringify(message.leftChoices));
})