I tried to use names()
on a reactiveVal
inside a shiny app without success.
Is this even possible? What are alternative ways to name reactive values in shiny apps?
My first attempt throws an error:
names(r()) <- "something"
Error in names(r()) <- "something" : invalid (NULL) left side of assignment
My second attempt as well:
names(r) <- "something"
Error in names(r) <- "something" : names() applied to a non-vector
Here is a minimal example app:
library(shiny)
ui <- fluidPage(mainPanel(textOutput("text")))
server <- function(input, output) {
r <- reactiveVal(1)
# names(r) <- "something"
output$text <- renderText(
paste0("The reactiveVal is ", r(),". It's name is ", names(r()),"."))
}
shinyApp(ui = ui, server = server)
The key is in the documentation on how to set values. From the docs:
Call the function with no arguments to (reactively) read the value; call the function with a single argument to set the value.
This means it gets a little bit esoteric and I personally prefer to use magrittr aliases and a pipe to keep things readable. The key steps for setting the names of your reactive value later on are:
r()
, to read the current value.isolate
to prevent any reactivity on this stepset_names
along with the name string.r
again with the named value as an argument, to set r
.library(shiny)
library(magrittr)
ui <- fluidPage(mainPanel(textOutput("text")))
server <- function(input, output) {
r <- reactiveVal(1 %>% set_names("something")) #setting the name on initial
isolate(r()) %>%
set_names("something else") %>%
r()
output$text <- renderText(
paste0("The reactiveVal is ", r(),". It's name is ", names(r()),"."))
}
shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
Shiny applications not supported in static R Markdown documents
Created on 2019-08-07 by the reprex package (v0.3.0)