2010-10-08 83 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)