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)
我猜问题是除法给出了一个非整数。 我怎样才能让第二个工作? 我需要创建一个零矩阵,其大小是通过方程计算计算出来的。
干杯
Why this works:
ncota <- 1
nslope <- 29
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)
But this doesn't?
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)
I guess the problem is that the division gives a noninteger number.
How can I get the second one work?
I need to create a zero matrix with its size calculated from a equation calculation.
cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您所要做的就是创建一个零矩阵,则不需要提供正确数量的零,只需提供一个并让 R 将其回收到所需的长度:
第二个失败的原因是
ncota * nslope * 4
不完全是 116:all.equal
显示,如果您允许浮点误差,则这些是相等的。?rep
包括以下内容:如果我们按照它所说的去做并添加一个小绒毛,
rep
确实会给出所需的 0 数量:正如 Hadley 所指出的(在评论中) ),可以使用 zapsmall 函数轻松添加此模糊:
If all you have to do is create a matrix of zeroes, you don't need to supply the correct number of zeroes, just supply one and let R recycle it to the required length:
The reason the second one fails is that
ncota * nslope * 4
is not exactly 116:all.equal
shows that these are equal if you allow for the floating point error.?rep
includes the following:and if we do as it says and add a small fuzz,
rep
does give the desired number of 0s:As noted by Hadley (in the comments), this fuzz can be easily added using the
zapsmall
function:您不需要使用
rep
。这工作得很好:You don't need to use
rep
. This works just fine: