Lachlan.00 - 2 months ago 5

R Question

I'm sure this question must be trivial but I couldn't find a similar question on stack overflow. I wish to merge

`array.A`

`array.B`

`result`

For example:

`array.A <- array(1:9, dim=c(3,3))`

array.B <- array(LETTERS[seq( from = 1, to = 9 )], dim=c(3,3))

> array.A

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

> array.B

[,1] [,2] [,3]

[1,] "A" "D" "G"

[2,] "B" "E" "H"

[3,] "C" "F" "I"

And I wish to merge them so that the resulting array would look like this:

`> result`

[,1] [,2] [,3]

[1,] ["A",1] ["D",4] ["G",7]

[2,] ["B",2] ["E",5] ["H",8]

[3,] ["C",3] ["F",6] ["I",9]

I've tried using

`cbind`

`rbind`

Thanks in advance.

Answer

It's not a typical kind of structure, but you can put `list`

objects inside a `matrix`

or `array`

:

```
out <- array(Map(list, array.A, array.B), dim=dim(array.A) )
# [,1] [,2] [,3]
#[1,] List,2 List,2 List,2
#[2,] List,2 List,2 List,2
#[3,] List,2 List,2 List,2
out[1,1]
#[[1]]
#[[1]][[1]]
#[1] 1
#
#[[1]][[2]]
#[1] "A"
out[1,1][[1]][1]
#[[1]]
#[1] 1
out[1,1][[1]][2]
#[[1]]
#[1] "A"
```

Source (Stackoverflow)

Comments