2010-10-08 75 views
1

为什么这个工程:R:为什么这不起作用?,矩阵,舍入错误?

ncota <- 1 
nslope <- 29 
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4) 

但是,这不?

ncota <- 1 
sini <- 0.1; sfin <- 1.5; spaso <- 0.05; nslope <- 1+((sfin-sini)/spaso) 
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4) 

我想问题是该部门给出了一个非整数。 我如何获得第二个工作? 我需要创建一个零矩阵,其大小通过等式计算来计算。

欢呼

+0

@Juan:跨多个列表交叉发布是不礼貌的。 stackoverflow和R-help)。 – 2010-10-09 18:33:35

+0

嗨。我以为他们在哪里不同的网站。我问了两个人,因为我不知道谁会回复和在哪里。 – skan 2010-10-20 13:39:18

回答

5

如果你所要做的就是创建零的矩阵,你并不需要提供零的正确数量,只需提供一个令R它回收到需要的长度:

matrix(0, ncota*nslope, 4) 

第二个失败的原因是,ncota * nslope * 4是不完全116:

> (ncota * nslope * 4) == 116 
[1] FALSE 
> all.equal(ncota * nslope * 4, 116) 
[1] TRUE 

all.equal表明,这些相等如果您允许浮点错误。

?rep包括以下内容:

Non-integer values of ‘times’ will be truncated towards zero. If 
‘times’ is a computed quantity it is prudent to add a small fuzz. 

,如果我们这样做,因为它说,并添加一个小绒毛,rep确实给0的所需数量:

> length(rep(0, times = ncota*nslope*4 + 0.00000001)) 
[1] 116 

正如哈德利指出(在评论中),可以使用zapsmall函数轻松添加此模糊:

> length(rep(0, times = zapsmall(ncota*nslope*4))) 
[1] 116 
+0

真棒答案;非常完整! – 2010-10-08 15:56:29

+2

在这种情况下另一个有用的功能是'zapsmall' – hadley 2010-10-08 16:14:43

+0

谢谢哈德利,忘记了这个功能。我已经在我的回答中添加了一条注释。 – 2010-10-08 16:20:06

1

你并不需要使用rep。这只是正常:

resul <- matrix(0,ncota*nslope,4)