This is my code:
letters <-letters[1:5]
ui <- fluidPage(
do.call(tabsetPanel,
letters %>%
purrr::map(~tabPanel(title = .x,
uiOutput(outputId = .x)))),
)
server <- function(input, output, session) {
1:5 %>% purrr::map( ~ {
output[[paste0(letters[.x])]] <-
renderUI({
h1(letters[.x])
})
})
}
shinyApp(ui, server)
This is my code. The main question here is to understand the syntax of the code inside the server function.
Why this code bellow doesn’t work:
1:5 %>% purrr::map(
~ output[[paste0(letters[.x])]] <-
renderUI({
h1(letters[.x])
})
)
And also, for this code that works why do I need to use { } inside map
1:5 %>% purrr::map( ~ {
output[[paste0(letters[.x])]] <-
renderUI({
h1(letters[.x])
})
})
Any help to understand this syntax?
>Solution :
To understand this let’s take a simpler example as this question is not related to shiny specifically.
out <- list(1:3, 5:7)
out
#[[1]]
#[1] 1 2 3
#[[2]]
#[1] 5 6 7
To take sum of each list element we can either do
purrr::map(out, sum)
#[[1]]
#[1] 6
#[[2]]
#[1] 18
Or using the ~ notation
purrr::map(out, ~sum(.x))
Now, if you want to do something "more" i.e if the function that you want to apply takes more than 1 step. So let’s say, you want to take square of the summed values you need to use the curly braces ({})
purrr::map(out, ~{
y <- sum(.x)
y^2
})
#[[1]]
#[1] 36
#[[2]]
#[1] 324
In this simple example, I know you can do this in 1 step as purrr::map(out, ~sum(.x)^2) but this is just to demonstrate the use of {} here.
If it get’s too complex as a general rule you can always use {} in your functions. So in the first case for taking sum you may do purrr::map(out, ~{sum(.x)}).