max
max

Reputation: 4521

How to compute the matrix of the sum of two dice rolls in R?

Is there an idiomatic way to compute the sum of two dice rolls in R, as a matrix?

This is the output I am seeking:

      [1]  [2]  [3]  [4]  [5]  [6]
[1]    2    3    4    5    6    7
[2]    3    4    5    6    7    8
[3]    4    5    6    7    8    9
[4]    5    6    7    8    9   10
[5]    6    7    8    9   10   11
[6]    7    8    9   10   11   12

Upvotes: 1

Views: 441

Answers (3)

Ght ja
Ght ja

Reputation: 21

sapply(seq(6), "+", seq(6))

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    2    3    4    5    6    7
#[2,]    3    4    5    6    7    8
#[3,]    4    5    6    7    8    9
#[4,]    5    6    7    8    9   10
#[5,]    6    7    8    9   10   11
#[6,]    7    8    9   10   11   12

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101753

Another base R option besides outer, using replicate

r <- t(replicate(6,1:6))+1:6

or

r <- (u <- replicate(6,1:6)) + t(u)

such that

> r
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2    3    4    5    6    7
[2,]    3    4    5    6    7    8
[3,]    4    5    6    7    8    9
[4,]    5    6    7    8    9   10
[5,]    6    7    8    9   10   11
[6,]    7    8    9   10   11   12

Upvotes: 2

Wart
Wart

Reputation: 560

The outer function is designed for taking the outer product of two vectors, but you can switch the function to "+".

outer(1:6, 1:6, "+")

Upvotes: 5

Related Questions