tags:

views:

60

answers:

2

Hello

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

+1  A: 

You don't need to use rep. This works just fine:

resul <- matrix(0,ncota*nslope,4)
Joshua Ulrich
+4  A: 

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:

matrix(0, ncota*nslope, 4)

The reason the second one fails is that ncota * nslope * 4 is not exactly 116:

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

all.equal shows that these are equal if you allow for the floating point error.

?rep includes the following:

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

and if we do as it says and add a small fuzz, rep does give the desired number of 0s:

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

As noted by Hadley (in the comments), this fuzz can be easily added using the zapsmall function:

> length(rep(0, times = zapsmall(ncota*nslope*4)))
[1] 116
Gavin Simpson
Awesome answer; very complete!
Joshua Ulrich
Another useful function in this circumstance is `zapsmall`
hadley
Thanks Hadley, had forgotten about that function. I've added a note on this to my answer.
Gavin Simpson
Thank you. Is strange that R need this trick
@user425895: R relies on floating point arithmetic. See the R FAQ entry 7.31 for further details: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f
Gavin Simpson