You probably want to use reactiveValues
and observeEvent
.
library(shiny)
library(colourpicker)
ui <- fluidPage(
colourInput('col', 'Select colour', 'purple'),
actionButton(inputId = 'OK', label = 'enter color'),
textOutput('couleurs')
)
server <- function(input, output) {
values <- reactiveValues(col_string = '')
observeEvent(input$OK, {
if (values$col_string == '') {
values$col_string <- paste0('"', input$col, '"')
} else {
values$col_string <- paste0(values$col_string, ', ', paste0('"', input$col, '"'))
}
})
output$couleurs <- renderText({ values$col_string })
}
shinyApp(ui = ui, server = server)
Here's an example using the selected colors in a sankey network. As I said in the comments, you're going to have to use paste0
or the sep = ""
argument of paste
so that the elements combined to make colorJS
are not separated by a space. That's why I asked you what the output of your paste command is. Notice the difference between these two commands and their output...
domain <- '"one", "two", "three"'
col_string <- '"#382743", "#916402", "#064713"'
paste('d3.scaleOrdinal().domain([', domain, '])', '.range([', col_string, '])')
# d3.scaleOrdinal().domain([ "one", "two", "three" ]) .range([ "#382743", "#916402", "#064713" ])
paste0('d3.scaleOrdinal().domain([', domain, '])', '.range([', col_string, '])')
# d3.scaleOrdinal().domain(["one", "two", "three"]).range(["#382743", "#916402", "#064713"])
Here's the minimal reproducible example (doesn't require a specifically formatted Excel spreadsheet that no one but you has access to)...
library(shiny)
library(colourpicker)
library(networkD3)
ui <- fluidPage(
colourInput('col', 'Select colour', 'purple'),
actionButton(inputId = 'OK', label = 'enter color'),
textOutput('couleurs'),
actionButton(inputId = 'plot', label = 'plot'),
sankeyNetworkOutput("splot")
)
server <- function(input, output) {
values <- reactiveValues(col_string = '')
observeEvent(input$OK, {
if (values$col_string == '') {
values$col_string <- paste0('"', input$col, '"')
} else {
values$col_string <- paste0(values$col_string, ', ', paste0('"', input$col, '"'))
}
})
output$couleurs <- renderText({ values$col_string })
observeEvent(input$plot, {
if (values$col_string != '') {
output$splot <- renderSankeyNetwork({
data <- data.frame(i = c(0, 0, 0),
j = c(1, 2, 3),
value = c(3, 1, 2),
lgroup = c("lgroup1", "lgroup2", "lgroup2"))
label <- data.frame(name = c("zero", "one", "two", "three"),
ngroup = c("ngroup1", "ngroup2", "ngroup2", "ngroup2"))
domain <- paste0("'", paste(unique(c(as.character(data$lgroup), as.character(label$ngroup))), collapse = "', '"), "'")
colorJS <-
paste0('d3.scaleOrdinal().domain([', domain, ']).range([', values$col_string, '])')
sankeyNetwork(Links = data, Nodes = label, Source = 'i', Target = 'j',
Value = 'value', NodeID = "name", NodeGroup = "ngroup",
LinkGroup = "lgroup", colourScale = colorJS)
})
}
})
}
shinyApp(ui = ui, server = server)