rarrayssequence

R create an array result of cutting (seq) of a data frame


I'm not comfortable with array manipulation (and English writing, sorry ..)

I have this data frame (aa):

aa<-data.frame(replicate(10,sample(0:17,30,rep=TRUE)))


  > aa
   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1  17  7  9  2  3  7 17  0 15   1
2  12  5 10 10  8 17 13  7  2   2
3  14 14  7  7 16  1 13  0 14   6
4  12 10 10 15  7  2  7 11  4   0
5   1  9  5  5  8 15 15 11  8  17
6   8  0  9  6  7 11  9 12  4  17
7  17  1 17  5 11  8 16  0  2  15
8  10  7 15  6 17  3  0 16 16  15
9   8  3 14 13 16  5 15  8 14  10
10 11 13 15  3 17 13 13  4 11  12
11  9 13  0  7  4 13 15  1  2   0
12  1  3 17 13 10  4 12  5  4  15
13  5  8  9  8  0  6 14 13  0   8
14 17 11 10  4 15 10  7  1  1   7
15  2  0 16  7 13 10 13  3 10   7
16  5  5 15  7  0 17 10 14 11   4
17 10 17  9 11  0  9  9 17  0   4
18 12  8  8 16 11  4 10 16  4   7
19  5  7 13 12 17 17 17 17  6   8
20 13 17  1  2  0  1  8  4 17  17
21 15 15  5 13  6 16  5  5 14  13
22 12  4  5  1  2  7 17  2  9   9
23 12  5 13 16  6  6 15  2 13  10
24  8  6 12  4  5 11  7 12 14  10
25  5 11 15  1 17  3  8 10  4   4
26  3 10  8 14  1 13 16  1 16  11
27 10  2 14 11  6  8 13  3  8  10
28 14  5  7 12  8 14 16  9 16  14
29  5 17 16 17 12  1  3  8  2   0
30  5 17 12  2  8  9  3  1 14  15

I would like to create an array which is the result of a cutting of dataframe (aa) like this (by seq of x elements, here for example 10): an array with 3 dimensions

 , , 1

       X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
    1  17  7  9  2  3  7 17  0 15   1
    2  12  5 10 10  8 17 13  7  2   2
    3  14 14  7  7 16  1 13  0 14   6
    4  12 10 10 15  7  2  7 11  4   0
    5   1  9  5  5  8 15 15 11  8  17
    6   8  0  9  6  7 11  9 12  4  17
    7  17  1 17  5 11  8 16  0  2  15
    8  10  7 15  6 17  3  0 16 16  15
    9   8  3 14 13 16  5 15  8 14  10
    10 11 13 15  3 17 13 13  4 11  12

, , 2
        X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
    11  9 13  0  7  4 13 15  1  2   0
    12  1  3 17 13 10  4 12  5  4  15
    13  5  8  9  8  0  6 14 13  0   8
    14 17 11 10  4 15 10  7  1  1   7
    15  2  0 16  7 13 10 13  3 10   7
    16  5  5 15  7  0 17 10 14 11   4
    17 10 17  9 11  0  9  9 17  0   4
    18 12  8  8 16 11  4 10 16  4   7
    19  5  7 13 12 17 17 17 17  6   8
    20 13 17  1  2  0  1  8  4 17  17

etc...

I've already tried this...

  aa_lag <-array(aa[1:10,],dim=c(dim(aa),3))

thank you so much for answer...


Solution

  • You can try

    aa1 <- t(aa)
    dim(aa1) <- c(10,10,3)
    aa2 <- aperm(aa1, c(2,1,3))
    

    Checking the results

     m1 <- as.matrix(aa[1:10,])
     dimnames(m1) <- NULL
     identical(m1, aa2[,,1])
     #[1] TRUE
    

    Or using seq

     lst <- lapply(seq(1,30, by=10), function(i) aa[i:(i+9),])
     aa3 <- array(unlist(lst), dim=c(10,10,3))
     identical(aa2, aa3)
     #[1] TRUE
    

    data

    set.seed(24)
    aa<-data.frame(replicate(10,sample(0:17,30,rep=TRUE)))