Reputation: 4521
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
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
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
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