r - Shiny App 反应性问题和范围问题
问题描述
我是闪亮的新手,我正在尝试构建一个应用程序,但我已经在这个问题上停留了一段时间。该应用程序的目的是让用户可以上传他们的数据,选择他们的自变量和因变量,选择他们的树数......等等,并最终通过随机森林脚本运行并显示输出。
但是,现在我坚持设置下拉输入,用户可以在其中选择他们的变量(来自他们上传的数据的标题)。它需要是响应式的,因此他们首先上传他们的数据,然后应用程序会自动知道在下拉菜单中放置什么,否则它将为 NULL。这是我的 ui.R 和 server.R 文件的副本。如果您知道可能出了什么问题,我们将不胜感激您的帮助。另外,感谢上周帮助我的人。我没有上传实际的 R 代码(只是图片),所以这对他们来说更具挑战性。
用户界面
library(shiny)
shinyUI(fluidPage(
headerPanel(title = "Upload File"),
sidebarLayout(
sidebarPanel(
fileInput("file","Upload the file"),
h5("Max file size is 5 MB"),
tags$hr(),
radioButtons("sep","Seperator", choices = c(Comma = ",", Period = ".", Tilde = "~",minus = "-")),
tags$hr(),
checkboxInput("header","Header", TRUE),
tags$hr(),
uiOutput("vx"),
tags$hr(),
uiOutput("vy"),
tags$hr(),
numericInput("MTRY", "Set the MTRY", 0, min = 0, max = 500, step = 1,
width = 100),
helpText("The MTRY should default to 0"),
numericInput("numtree", "Number of Trees", 500, min = 30, max = 10000, step = 100,
width = 100)
),
mainPanel(
tableOutput("input_file")
)
)
)
)
服务器.R
library(shiny)
shinyServer(function(input, output) {
output$input_file <- renderTable({
file_to_read = input$file
if(is.null(file_to_read)){
return()
}
dat1 <- read.table(file_to_read$datapath, sep = input$sep, header = input$header)
return(dat1)
})
reactive1 = reactive({
if(is.null(dat1))
return()
D <- colnames(dat1)
reactive1[[1]] = D
reactive1[[2]] = D[1]
reactive1
})
output$vx <- renderUI({
selectInput("cols", "Select Dependent Variable",
choices = colnames(reactive1()[[1]]), selected = reactive1()[[2]][1])
})
output$vy <- renderUI({
selectInput("cols", "Select Independent Variables",
choices = colnames(reactive1()[[1]]), selected = reactive1()[[2]][1], multiple = T)
})
})
这是上传 csv 后应用程序的外观:
解决方案
关键是使输入数据反应和更新选择输入基于反应数据帧。见下文:
ui <- fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
tags$hr(),
selectInput("vars", "Label",choices = c("NULL"))
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output, session) {
df1 <- reactive({
req(input$file1)
read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
})
observeEvent(df1(), {
updateSelectInput(session, "vars", choices = names(df1()))
})
}
shinyApp(ui, server)
如果这回答了您的问题,请发表评论。
推荐阅读
- imagemagick - 确定图像中有多少种独特的颜色
- google-bigquery - PowerBI - BigQuery 直接导入不会自动更新架构以包含新列
- c - 动态库中 RTLD_NODELETE 和 RTLD_NOLOAD 的目的是什么?
- java - 正在研究一本旧 JAVA 书籍的示例问题,我已经发布了我的答案,只是不确定。有人可以验证答案是否正确
- python-3.x - 我正在尝试使用 TOR 使用硒:错误
- html - 如何将列和行移动到中心
- javascript - Javascript与Python通信
- vba - MS-Access 中的提交事务无法写入数据库
- typescript - 如何正确记录(TSDoc)导出的类
- django - Django,使用 timedelta 将后续日期添加到发票日期