Find minimum value of two dice roll in R

Viewed 111

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
3 Answers
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

*apply loops are loops just like for loops but they make nice one-liners.

sapply(1:6, function(y) sapply(1:6, function(x) min(x, y)))
#     [,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

@user2974951's answer is way better, but here's my solution anyways:

a <- matrix(0, nrow = 6, ncol = 6)
for (i in 6:1){
  a[,i] <- i
  a[i,] <- i
}
a
#>     [,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
Related