for循环 - 替换的长度为零 [英] for Loop - Replacement has length zero

查看:424
本文介绍了for循环 - 替换的长度为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环的小问题。这里是循环的代码:

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

这将返回以下错误:标题[i] < - 输入中的错误


$ id:replacement的长度为零


ui.R

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

< server.R

  server<  -  function(input,output,session){
输出$ textboxes< - renderUI({
if(input $ count == 0)
return(NULL)
lapply(1:input $ count,function(i){
id< - paste0(text,i)
print(id)//它打印text1,text2,text3
numericInput(id,NULL ,值= abc)
打印(输入$ text1)//应该打印abc值,但不是,为什么?
$ b))
})
}


解决方案

这个错误表明你的输入ID是NULL或者长度为0的矢量:确保索引是正确的。

另外,在R中,通常最好避免循环,因为它们往往很慢:请参阅为什么循环缓慢吗?几乎总是有一种避免使用for循环和使用矢量化函数的方法,尽管现在的例子并没有提供足够的细节来实际建议一个函数。


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

    })
  })
}

解决方案

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.

这篇关于for循环 - 替换的长度为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆