4

I have a little problem with a loop. Here is the code of the loop:

for (i in 1:length(input$count))
{       
    id<-paste("text",i)
    titles[i]<-input$id
}

This returns the following error

Error in titles[i] <- input$id : replacement has length zero

ui.R

library(shiny)
ui <- fluidPage(
numericInput("count", "Number of textboxes", 3),                  
hr(),
uiOutput("textboxes")
)

server.R

server <- function(input, output, session) {
   output$textboxes <- renderUI({
   if (input$count == 0)
      return(NULL)
  lapply(1:input$count, function(i) {
      id <- paste0("text", i)
      print(id)            // its prints the text1, text2,text3
      numericInput(id, NULL, value = abc)
      print(input$text1)   //it should print value abc , but it is not, why??

    })
  })
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user3735381
  • 53
  • 1
  • 2
  • 5
  • You might want to read [How do I ask a good question](http://stackoverflow.com/help/how-to-ask), which enhances the probability for getting a useful answer _drastically_. You might find [ESR](https://en.m.wikipedia.org/wiki/Eric_S._Raymond)'s excellent essay [How To Ask Questions The Smart Way](http://catb.org/~esr/faqs/smart-questions.html) helpful, too. – Markus W Mahlberg Mar 14 '15 at 14:07

1 Answers1

7

This error indicates that your input id is either NULL or a length 0 vector: make sure the indices are correct.

Additionally, in R it is usually best to avoid for loops as they tend to be pretty slow: see Why are loops slow in R?. There's almost always a way to avoid using a for loop and using a vectorised function instead, although the example as it stands doesn't provide enough detail to actually suggest a function.

Community
  • 1
  • 1
Gregory
  • 94
  • 3
  • Thank you Gregory..you are correct, when i tried to print the id value , it shows the value NULL. But i am not getting why it is showing NULL. I have edited my question and attached the ui.R and server.R also. Please have a look at the code and help me – user3735381 Mar 18 '15 at 09:47
  • The input won't exist yet if you try printing it there. If you want to show the elements in your uiOutput they have to be returned in a list from the renderUI expression. You need to save the numericInputs in a return list. – Gregory Mar 18 '15 at 19:05