skan
skan

Reputation: 7720

R: Why this doesn't work?, matrix, rounding error?

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

Upvotes: 1

Views: 563

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174803

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

Upvotes: 5

Joshua Ulrich
Joshua Ulrich

Reputation: 176658

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

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

Upvotes: 1

Related Questions