Reputation: 128
I have a nxp
data frame and I want to convert it to an array with n
matrices where each matrix is, let's say, ixj
where i+j = p
. Considering the following reprex:
library(tidyverse)
df <- tribble(
~x1, ~x2, ~x3, ~x4,
1, 2, 3, 4,
5, 6, 7, 8)
The desired result is an array with 2 matrices similar to the one produced by:
array(1:8, c(2,2,2))
Would anybody have an efficient method to obtain such results in high dimensional data frames?
Upvotes: 0
Views: 33
Reputation: 37879
With baseR and array
:
array(t(df), c(2, 2, 2))
#, , 1
#
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
#
#, , 2
#
# [,1] [,2]
#[1,] 5 7
#[2,] 6 8
Upvotes: 2