I am having trouble reducing a lengthy if-else statement. In my Shiny app, the user enters a value for 'num_fact' (the number of factors) that is used several times through the code to dynamically generate UI elements.
I've tried using lapply() but I haven't been able to make it work.
Based upon the number of factors, two dynamic UI elements are created (levels and treatments) that each have the same number of inputs as the number of factors. I want to pull values from those UI elements.
The following code works.
if (num_fact == 1) {
levels <- c(input$n_F1)
treatments <- c((input$t_F1)/100)
} else if (num_fact == 2) {
levels <- c(input$n_F1, input$n_F2)
treatments <- c((input$t_F1)/100, (input$t_F2)/100)
} else if (num_fact == 3) {
levels <- c(input$n_F1, input$n_F2, input$n_F3)
treatments <- c((input$t_F1)/100, (input$t_F2)/100, (input$t_F3)/100)
} else if (num_fact == 4) {
levels <- c(input$n_F1, input$n_F2, input$n_F3, input$n_F4)
treatments <- c((input$t_F1)/100, (input$t_F2)/100, (input$t_F3)/100, (input$t_F4)/100)
}
But it's lengthy and I want to improve it. I've successfully applied lapply() to dynamically generate UI elements based upon the number of factors, as follows:
output$ui_factor_levels <- renderUI({
req(input$num_fact)
fluidRow(
lapply(1:(as.numeric(input$num_fact)), function(i) {
column(4, numericInput(paste0("n_F", i), h5(paste0("Factor ", i)), value = 2))
})
)
})
I can't seem to get the if-else statement to work as an apply() function. I think my problem is related to how levels and treatments are being generated.
Aucun commentaire:
Enregistrer un commentaire