# array example

library(abind) # generalization of cbind and rbind.

tt <- matrix(1:24, nrow=2, byrow=TRUE)

tt %>% apply(1, function(x) x)
#tt %>% t()

tt %>% apply(1, function(x){
r <- x[1: 4]
g <- x[5: 8]
b <- x[9:12]
list(R=r,G=g,B=b)
})

tt %>% apply(1, function(x){
r <- matrix(x[1: 4], 2,2, byrow=T)
g <- matrix(x[5: 8], 2,2, byrow=T)
b <- matrix(x[9:12], 2,2, byrow=T)
list(R=r,G=g,B=b)
})

tt %>% apply(1, function(x){
r <- matrix(x[1: 4], 2,2, byrow=T)
g <- matrix(x[5: 8], 2,2, byrow=T)
b <- matrix(x[9:12], 2,2, byrow=T)
array(c(r,g,b), dim=c(2,2,3))
})

res <- tt %>% apply(1, function(x){
r <- matrix(x[1: 4], 2,2, byrow=T)
g <- matrix(x[5: 8], 2,2, byrow=T)
b <- matrix(x[9:12], 2,2, byrow=T)
list(array(c(r,g,b), dim=c(2,2,3),
dimnames=list(height=str_c("h",1:2),width=str_c("w",1:2),Color=c("R","G","B"))) )
})

res %>% do.call(c,.)
#res %>% do.call(c,.) %>% abind()  # along=3
res %>% do.call(c,.) %>% abind(., along=4)
res %>% do.call(c,.) %>% abind(., along=4) %>% aperm(., c(4,1,2,3))

Blog Owner

Subscribe
Notify of