Reputation: 2995
Is it possible to generate a reactiveValues
where the variable names are given by a certain list list_of_names
? These variables could for example store a boolean indicating the state of the corresponding variable.
Imagine I have a list x
:
x <- lapply(LETTERS, function(i) TRUE)
names(x) <- LETTERS
Can I generate a reactiveValues
rv
from x
that behaves like x
?
I haven't been to able to do so, and all I could came up with was something like this:
ui <- fluidPage(
textOutput("boolean")
)
server = function(input, output, session){
nms <- LETTERS[1:10]
### lines that I would change
rv <- reactiveValues(A = TRUE)
for (n in nms) {rv[[n]] <- TRUE}
###
output$boolean <- renderText(rv[["D"]])
}
shinyApp(ui,server)
It works, but I'm sure there must be a simpler and "cleaner" way to do this, as x
and rv
are quite similar. Thanks to anyone that can help me on this one.
Upvotes: 5
Views: 2026
Reputation: 818
A simple way to do it is to call your vector as arguments of the function reactiveValues :
ui <- fluidPage(
textOutput("boolean")
)
server = function(input, output, session){
x <- as.list(rep(T,10))
names(x) <- LETTERS[1:10]
# x as arguments of reactiveValues function
rv <- do.call("reactiveValues",x)
# still works
output$boolean <- renderText(rv[["D"]])
}
shinyApp(ui,server)
EDIT : to me, it is not possible to maintain the original order of the vector. An other way is to keep it somewhere else (if possible), then to call it whenever needed :
ui <- fluidPage(
textOutput("boolean")
)
server = function(input, output, session){
x <- as.list(rep(T,10))
names(x) <- rev(LETTERS[1:10])
true_order <- levels(factor(names(x),names(x)))
# x as arguments of reactiveValues function
rv <- do.call("reactiveValues",x)
# still works
output$boolean <- renderText({
p <- names(x)
paste0(p[sapply(true_order,function(x,p){which(p == x)},p=p)], collapse = "-")
}
)
}
Upvotes: 7