Home > Software engineering >  I'm trying to take the product of the columns in a matrix using R. What am I doing wrong?
I'm trying to take the product of the columns in a matrix using R. What am I doing wrong?

Time:08-31

The problem:

The problem

What I get:

What I get

What could be the problem here? I believe I'm doing everything just like asked but still get completely different results.

CodePudding user response:

This is the result of changes (improvements) to R's default random number generator, see help("set.seed").

RNGversion('4.2.0') #current behavior
set.seed(10)
m1 <- matrix(sample(1:10, 25, replace = TRUE), nrow = 5)
apply(m1, 2, prod)
#[1] 30240 11760  8960  2520  9000

RNGversion('3.1.0') #behavior in old R versions
#Warning message:
#  In RNGkind("Mersenne-Twister", "Inversion", "Rounding") :
#  non-uniform 'Rounding' sampler used
set.seed(10)
m1 <- matrix(sample(1:10, 25, replace = TRUE), nrow = 5)
apply(m1, 2, prod)
#[1]   840   945  2016   540 10080

CodePudding user response:

The issue here is that the behaviour of set.seed was different in versions of R prior to 3.6.0. To get the expected values, you need to change the sample.kind parameter.

Old version (gives the expected values):

set.seed(10, sample.kind = "Rounding")
m1 <- matrix(sample(1:10, 25, replace = TRUE), nrow = 5, ncol = 5)
m1

     [,1] [,2] [,3] [,4] [,5]
[1,]    6    3    7    5    9
[2,]    4    3    6    1    7
[3,]    5    3    2    3    8
[4,]    7    7    6    4    4
[5,]    1    5    4    9    5

Set it back to the newer default:

set.seed(10, sample.kind = "Rejection")
m1 <- matrix(sample(1:10, 25, replace = TRUE), nrow = 5, ncol = 5)
m1
     [,1] [,2] [,3] [,4] [,5]
[1,]    9    7   10    6    9
[2,]   10    3    2    7    2
[3,]    7    8    8    6   10
[4,]    8   10    8    2    5
[5,]    6    7    7    5   10
  •  Tags:  
  • r
  • Related