在R中简单的产生“替换长度为零”的循环。在R [英] Simple for loop in R producing "replacement has length zero" in R

查看:229
本文介绍了在R中简单的产生“替换长度为零”的循环。在R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,所以在C和Python中似乎工作得很好,在R.
中出人意料地分解了。我试图计算前1000个斐波纳契数的乘积。以下是完整的代码:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ Fibonacci< -rep(0,1000)
Fibonacci [0] <-1
Fibonacci [1] <-1
产品< -1

for(i in 2:1000)
{
Fibonacci [i]< ;-( Fibonacci [i-1])+(Fibonacci [i-2])
Product< -Fibonacci [i] * Product
}

Fibonacci [1000]
产品

这将返回以下错误: (Fibonacci [X-1])+(Fibonacci [X-2])中的误差:在Fibonacci [i] <-Fibonacci [X-1]
更换长度为零

我倾向于认为我误解了不同的元素一个数组(可能是向量描述中的i-2是不正确的),但是在过去的一个半小时里我没有找到任何东西,这可能会帮助我纠正它。
所以,任何洞察问题的原因将不胜感激。

预先感谢您。

  Fibonacci [1] < -1 
Fibonacci [2]< -1
产品< -1
(3:1000中的i)
{


$(其余部分与你的问题一样)

问题是 Fibonacci [0] 这是一个0长度的数字。当 i = 2 时,这个表达式的右边是 numeric(0)

$ b Fibonacci [i]< ;-( Fibonacci [i-1])+(Fibonacci [i-2])
$ b

  $ c> 


I am a novice in R, and so what seemed to work fine in C and Python, surprisingly breaks down in R. I am trying to calculate the product of the first 1000 Fibonacci numbers. Here is the full code:

#PRRODUCT OF FIBONACCI NUMBERS
Fibonacci<-rep(0, 1000)
Fibonacci[0]<-1
Fibonacci[1]<-1
Product<-1

for (i in 2:1000)
{
    Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])
    Product<-Fibonacci[i]*Product
}

Fibonacci[1000]
Product

This returns the following error:

Error in Fibonacci[i] <- (Fibonacci[X - 1]) + (Fibonacci[X - 2]) : 
  replacement has length zero

I am inclined to think I have misunderstood operating with different elements of an array (perhaps the i-2 in the vector description is not correct), but I haven't found anything over the past hour and a half which would have helped me correct it. So, any insights into the cause of the problem would be most appreciated.

Thank you in advance.

解决方案

Arrays in R are 1-based.

Fibonacci[1]<-1
Fibonacci[2]<-1
Product<-1
for (i in 3:1000)
{

(the remainder as in your question)

The problem is Fibonacci[0] which is a 0-length numeric. When i = 2, this expression has a right hand side of numeric(0):

Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])

这篇关于在R中简单的产生“替换长度为零”的循环。在R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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