Shiny assign reactive variable from input using lo

2019-07-31 15:57发布

I'm trying to assign reactive variable based on my input using loop. For example, I want to select the column (from input) in iris data set. Then get the unique value from that column. And I want to do this in the loop. I find it works for my 'joke' variable, but not for my 'Group[[paste0('Gcol',i)]]' variable. I've been searching answer for this for days.

Thank you for your help in advance!

library(shiny)
data=iris


ui <- fluidPage(

titlePanel("Old Faithful Geyser Data"),

sidebarLayout(
  sidebarPanel(

     fluidRow(
       column(9,wellPanel(lapply(1:5, function(i) {
         selectizeInput(paste0('GroupVar',i), paste0('Group ',i), choices = sort(colnames(data)),
                        options = list(placeholder = 'Select one',
                                       onInitialize = I('function() { 
this.setValue(""); }')))
       })
       )))
  ),

  mainPanel(
             fluidRow(column(6, wellPanel(
                lapply(1:5, function(i) {
                  uiOutput(paste0('GroupOpt', i))
                })
              ))),
             textOutput("try4"),
             textOutput("try2"),
             textOutput("try21"),
             textOutput("try3"),
             textOutput("try")
  )
)
)

server <- function(input, output) {

Group=reactiveValues()

for (i in 1:5){
Group[[paste0('Gcol',i)]]=reactive({
data[,which(colnames(data)==
input[[paste0('GroupVar',i)]])]})
}

joke=reactive({data[,which(colnames(data)==input[[paste0('GroupVar',1)]])]})

lapply(1:5, function(i) { output[[paste0('GroupOpt',i)]] = renderUI({
selectInput(paste0("GroupOpt",i), "Select group",multiple=TRUE,
            sort(as.character(unique(Group[[paste0('Gcol',i)]])))
 )
  })})

output$try4 = renderText({print(paste0('it 
is',input[[paste0('GroupVar',1)]]))})
output$try2 = renderText({print(dim( Group[[paste0('Gcol',1)]]()))})
output$try21 = renderText({print(class( Group[[paste0('Gcol',1)]]()))})
output$try3 = 
renderText({print(which(colnames(data)==input[[paste0('GroupVar',1)]]))})

 output$try = renderText({print(unique(as.character(joke())))})


}

# Run the application 
shinyApp(ui = ui, server = server)

1条回答
萌系小妹纸
2楼-- · 2019-07-31 16:23

data[, which(colnames(data)=="Species")] is not a dataframe, this is the column Species, a factor. If you want to allow a one-column dataframe, do data[, which(colnames(data)=="Species"), drop=FALSE]

Replace your loop with the following one, and your app works (but maybe not as you expect; I'm not sure to understand what you want).

  for (i in 1:5){
    local({
      ii <- i
      Group[[paste0('Gcol',ii)]]=reactive({
        data[,which(colnames(data)==input[[paste0('GroupVar',ii)]])]})
    })
  }
查看更多
登录 后发表回答