shiny
新手,现在已经为此苦苦挣扎了两天多。
我创建了一个应用程序,用户在其中加载 .csv
数据文件并选择一个或多个变量,其名称在应用程序中显示为复选框。当一个复选框被选中时,一个具有相同名称的新复选框出现在下面,当它也被点击时,一个 textAreaInput
出现在它旁边,用户可以在其中添加构成目标变量的变量名称作为比例.这是该应用程序的过度简化版本:
library(shiny)
ui <- fluidPage(
mainPanel(
fileInput(inputId = "file", label = "Choose File", multiple = TRUE, accept = ".csv"),
uiOutput(outputId = "varCheckBoxesIndivScores"),
column(width = 3,
uiOutput(outputId = "selectedScoresCheckBoxes")),
conditionalPanel(condition = "input.selectedScoresCheckBoxes",
column(width = 6,
uiOutput(outputId = "variablesConstitutingScale"))
)
)
)
server = function(input, output, session) {
df <- reactive({
if(is.null(input$file)) {
return(NULL)
} else {
tbl <- fread(input$file$datapath, stringsAsFactors = TRUE)
return(tbl)
}
})
output$varCheckBoxesIndivScores <- renderUI({
if(is.null(df())) {
return(NULL)
} else if(!is.null(df())) {
return(tags$div(align = "left",
class = "multicol",
checkboxGroupInput(inputId = "varCheckBoxesIndivScores",
label = "Select variables",
choices = colnames(df()))))
}
})
output$selectedScoresCheckBoxes <- renderUI({
if(is.null(df())) {
return(NULL)
} else if(!is.null(df())) {
return(tags$div(align = "left",
checkboxGroupInput(inputId = "selectedScoresCheckBoxes",
label = "",
choices = input$varCheckBoxesIndivScores)))
}
})
output$variablesConstitutingScale <- renderUI({
if(is.null(df())) {
return(NULL)
} else if(!is.null(df()) & length(input$selectedScoresCheckBoxes > 0)) {
var.list.input.fields <- lapply(input$selectedScoresCheckBoxes, function(i) {
textAreaInput(inputId = "i", label = paste("Variables constituting scale", i), width = "700px", height = "100px", value = NULL)
})
var.list.input.fields
}
})
}
shinyApp(ui = ui, server = server)
要加载的数据是这样生成的(只是摘录,真实的有更多的列和案例):
library(data.table)
x <- data.table(ID = c(2201:2220), VAR1 = rnorm(n = 20, mean = 10, sd = 2),
VAR2 = rnorm(n = 20, mean = 100, sd = 20), VAR3 = 1:20, VAR4 = 21:40,
VAR5 = 41:60, VAR6 = 61:80, VAR7 = 81:100)
write.csv(x = x, file = "/tmp/test_data.csv", row.names = FALSE)
它工作正常,没有错误。在每个生成的 textAreaInput
字段中输入变量名称后,它的外观如下:
但是,我想从每个动态生成的 textAreaInput
中获取用户输入并将其存储在如下列表中:
list(VAR1 = "VAR3 VAR4 VAR5", VAR2 = "VAR6 VAR7")
或
list(VAR1 = "VAR3", "VAR4", "VAR5", VAR2 = "VAR6", "VAR7")
在应用程序的服务器部分中供将来使用。
我尝试遵循 this 中的解决方案线程,但我没有成功找到任何解决方案并且感到很困惑。有人可以帮忙吗?
最佳答案
首先,您要确保为每个动态添加的元素分配一个唯一的名称。您刚刚对示例中的字母“i”进行了硬编码。你想要类似的东西
textAreaInput(inputId = paste0("varconst_",i), label = paste("Variables constituting scale", i),
width = "700px", height = "100px", value = NULL)
然后你可以用这样的东西观察那些文本框
observeEvent(lapply(paste0("varconst_", input$selectedScoresCheckBoxes), function(x) input[[x]]), {
obj <- Map(function(x) input[[paste0("varconst_",x)]], input$selectedScoresCheckBoxes)
dput(obj)
})
在这里,我只是使用 dput
将列表转储到控制台,以便您可以在更新时看到它,但您可以用它做任何您想做的事情。
关于R Shiny 将来自多个动态生成的 textAreaInput 字段的用户输入存储在服务器部分的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621348/