Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for Loop - Replacement has length zero

Tags:

for-loop

r

shiny

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??

    })
  })
}
like image 223
user3735381 Avatar asked Oct 26 '25 03:10

user3735381


1 Answers

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.

like image 96
Gregory Avatar answered Oct 27 '25 17:10

Gregory