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
外函数旨在取两个向量的外积,但您可以将函数切换为“+”。
outer(1:6, 1:6, "+")
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.