Generating matrices / using external

I am a new user (~ 1 day) R. I try to create all 216 results of three six-sided death rolls. The point is then to apply some function to each triplet (say, to the maximum nominal value). This is what I came up with:

mat <- matrix(numeric(0), ncol=3) for (i in 1:6) { for (j in 1:6) { for (k in 1:6) { mat <- rbind(mat, c(i, j, k)) } } } # find maximum of each outcome apply(mat, 1, max) 

Is there a better and more concise way to do this with R? I would like to use outer as follows:

 outer(1:6, outer(1:6, 1:6, max), max) 

but with an error

Error in the external (1: 6, 1: 6, max.): Dims [product 36] do not match the length of the object [1]

+5
source share
1 answer

We can use expand.grid to create combinations in data.frame , convert to matrix and get the maximum value of each row rowMaxs from library(matrixStats) .

 library(matrixStats) rowMaxs(as.matrix(expand.grid(rep(list(1:6),3)))) #[1] 1 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 2 #[38] 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 3 3 #[75] 3 4 5 6 3 3 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 4 4 4 #[112] 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 #[149] 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 #[186] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 

Or we can use pmax with expand.grid

 do.call(pmax, expand.grid(rep(list(1:6),3))) 

Or, as @Ben Bolker suggested, we can also use apply with MARGIN=1

 apply(expand.grid(rep(list(1:6),3)),1,max) 

Another option is outer with pmax .

 c(outer(1:6, outer(1:6, 1:6, FUN=pmax), FUN= pmax)) #[1] 1 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 2 #[38] 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 3 3 #[75] 3 4 5 6 3 3 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 4 4 4 #[112] 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 #[149] 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 #[186] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 

Or outer with Vectorize d max

 f1 <- function(x,y) max(x,y) c(outer(1:6, outer(1:6, 1:6, Vectorize(f1)), Vectorize(f1))) 
+6
source

Source: https://habr.com/ru/post/1235953/


All Articles