在类似的帖子 ( How to align a group of checkboxGroupInput in R Shiny) 中,复选框仅垂直对齐(如我的示例)或仅水平对齐(R Shiny display checkboxGroupInput horizontally)。我想知道是否有一种方法可以在两种意义上(在列中)实现这一点。
library(shiny)
examplesubset<-read.table(text="
elements locations
element_One A,M,P,R
element_Two A,B,C,M,P,E,I
element_Three G,M,T,F,O,H,A,B,C,D" , header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)
ui<-fluidPage(
tags$head(tags$style(HTML("
.multicol {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
-moz-column-fill: auto;
-column-fill: auto;
}
"))),
titlePanel("Panel"),
sidebarLayout(
sidebarPanel(
selectInput("elements", "Select elements:",
choices=examplesubset$elements)
) ,
mainPanel(
fluidRow(
column(3,
uiOutput("checkboxesui")
))))
)
server<-function(input, output,session) {
elementsselected<-reactive({
sp<-examplesubset[examplesubset$elements==input$elements,]
sp<-droplevels(sp)
})
locationsreactive<- reactive({
j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
j<-droplevels(j)
})
output$checkboxesui<-renderUI({
tags$div(align = 'left',
class = 'multicol',
checkboxGroupInput("locationscheckboxes", "locations",
choices=levels(locationsreactive())
, selected=c() )
)
})
}
shinyApp(ui = ui, server = server)
最佳答案
下面的代码应该可以解决问题。您需要将 CSS 列应用到它们所在位置下方的 div,然后从复选框上方和下方移除填充,我还将列填充更改为平衡:
library(shiny)
examplesubset<-read.table(text="
elements locations
element_One A,M,P,A,R,T
element_Two A,B,C,M,P,E,I,N,S
element_Three G,M,T,F,S,V,P" , header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)
ui<-fluidPage(
tags$head(tags$style(HTML("
.multicol .shiny-options-group{
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
-moz-column-fill: balanced;
-column-fill: balanced;
}
.checkbox{
margin-top: 0px !important;
-webkit-margin-after: 0px !important;
}
"))),
titlePanel("Panel"),
sidebarLayout(
sidebarPanel(
selectInput("elements", "Select elements:",
choices=examplesubset$elements)
) ,
mainPanel(
fluidRow(
column(3,
uiOutput("checkboxesui")
))))
)
server<-function(input, output,session) {
elementsselected<-reactive({
sp<-examplesubset[examplesubset$elements==input$elements,]
sp<-droplevels(sp)
})
locationsreactive<- reactive({
j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
j<-droplevels(j)
})
output$checkboxesui<-renderUI({
tags$div(align = 'left',
class = 'multicol',
checkboxGroupInput("locationscheckboxes", "locations",
choices=levels(locationsreactive())
, selected=c() )
)
})
}
shinyApp(ui = ui, server = server)
另一种选择是使用 CSS flexbox:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
这将解决您描述的排序问题,但您需要考虑 shiny-options-group div 的大小,以使所有内容都符合您的要求,具体取决于您的内容。重新排序您的复选框选项可能更容易,以便它们以您想要的方式显示。
关于css - 垂直和水平对齐 checkBoxGroupInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42742191/