library(sortable)
This example demonstrates how to use custom sortable widgets with any shiny object.
## Example shiny app to create a plot from sortable inputs
library(shiny)
library(htmlwidgets)
library(sortable)
library(magrittr)
<- function(df){
colnames_to_tags lapply(
colnames(df),
function(co) {
tag(
"p",
list(
class = class(df[, co]),
$span(class = "glyphicon glyphicon-move"),
tags$strong(co)
tags
)
)
}
)
}
<- fluidPage(
ui fluidRow(
class = "panel panel-heading",
div(
class = "panel-heading",
h3("Dragging variables to define a plot")
),fluidRow(
class = "panel-body",
column(
width = 3,
$div(
tagsclass = "panel panel-default",
$div(class = "panel-heading", "Variables"),
tags$div(
tagsclass = "panel-body",
id = "sort1",
colnames_to_tags(mtcars)
)
)
),column(
width = 3,
# analyse as x
$div(
tagsclass = "panel panel-default",
$div(
tagsclass = "panel-heading",
$span(class = "glyphicon glyphicon-stats"),
tags"Analyze as x (drag here)"
),$div(
tagsclass = "panel-body",
id = "sort2"
)
),# analyse as y
$div(
tagsclass = "panel panel-default",
$div(
tagsclass = "panel-heading",
$span(class = "glyphicon glyphicon-stats"),
tags"Analyze as y (drag here)"
),$div(
tagsclass = "panel-body",
id = "sort3"
)
)
),column(
width = 6,
plotOutput("plot")
)
)
),sortable_js(
"sort1",
options = sortable_options(
group = list(
name = "sortGroup1",
put = TRUE
),sort = FALSE,
onSort = sortable_js_capture_input("sort_vars")
)
),sortable_js(
"sort2",
options = sortable_options(
group = list(
group = "sortGroup1",
put = htmlwidgets::JS("function (to) { return to.el.children.length < 1; }"),
pull = TRUE
),onSort = sortable_js_capture_input("sort_x")
)
),sortable_js(
"sort3",
options = sortable_options(
group = list(
group = "sortGroup1",
put = htmlwidgets::JS("function (to) { return to.el.children.length < 1; }"),
pull = TRUE
),onSort = sortable_js_capture_input("sort_y")
)
)
)
<- function(input, output) {
server $variables <- renderPrint(input[["sort_vars"]])
output$analyse_x <- renderPrint(input[["sort_x"]])
output$analyse_y <- renderPrint(input[["sort_y"]])
output
<- reactive({
x <- input$sort_x
x if (is.character(x)) x %>% trimws()
})
<- reactive({
y $sort_y %>% trimws()
input
})
$plot <-
outputrenderPlot({
validate(
need(x(), "Drag a variable to x"),
need(y(), "Drag a variable to y")
)<- mtcars[, c(x(), y())]
dat names(dat) <- c("x", "y")
plot(y ~ x, data = dat, xlab = x(), ylab = y())
})
}shinyApp(ui, server)