Search code examples
rmindice

Find minimum value of two dice roll in R


Instead of using a loop to find a minimum of two dice roll in R such as:

Min <- matrix(0, nrow=6, ncol=6)
d1 <- 1:6
d2 <- 1:6
for(k in 1:6){
  for(j in 1:6){
    Min[k,j] <- min( c(d1[k], d2[j]) )
  }
}

Is there a simpler way or shorter code to get the following result?

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    1    1    1
[2,]    1    2    2    2    2    2
[3,]    1    2    3    3    3    3
[4,]    1    2    3    4    4    4
[5,]    1    2    3    4    5    5
[6,]    1    2    3    4    5    6

Solution

  • outer(d1,d2,pmin)
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    1    1    1    1    1    1
    [2,]    1    2    2    2    2    2
    [3,]    1    2    3    3    3    3
    [4,]    1    2    3    4    4    4
    [5,]    1    2    3    4    5    5
    [6,]    1    2    3    4    5    6