Emil Lykke Jensen
Emil Lykke Jensen

Reputation: 409

How to build a 'for' loop with input$i in R Shiny

In my shiny app, I build a a number of checkboxes using a for loop, like this:

landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island")

landecheckbox <- c()

for (land in landelist){
  landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>")
  landecheckbox <- c(landechek, landecheckbox)
}

and then I print it to my HTML:

  output$inputdata <- renderText({

    landecheckbox

  })

So far so good! However when I try to do the same loop reversed, it wont let me. Here is what I'm trying to do:

filterdata <- data

filterland <- c()

for (landeselect in landelist) if (input$landeselect == TRUE) filterland <- c(landeselect, filterland)

filterdata <- filterdata %>% filter(filterdata$Contry %in% filterland)

So what I want it to do, is to look for the input id "Danmark", then "Tjekkiet", then "Østrig" and so on. What it does is, that it looks for the input id "landeselect" 9 times!

So my question is, how can I fix that?

Upvotes: 1

Views: 1349

Answers (1)

Rorschach
Rorschach

Reputation: 32446

Use [[ or [ if you want to subset by string names, not $. From Hadley's Advanced R, "x$y is equivalent to x[["y", exact = FALSE]]."

## Create input
input <- `names<-`(lapply(landelist, function(x) sample(0:1, 1)), landelist)
filterland <- c()

for (landeselect in landelist) 
    if (input[[landeselect]] == TRUE)  # use `[[` to subset
        filterland <- c(landeselect, filterland)

Upvotes: 1

Related Questions