I want to output the array created by array of R as a data frame along with the index of the array.

Asked 2 years ago, Updated 2 years ago, 115 views

How do I print an array of R's array to a data frame?

Specifically, if there is an n-dimensional array, I would like to output it as follows.
The first column contains the first-dimensional index number,
The second column contains the second-dimensional index number,
·
·
·
The nth column contains the nth dimension index number,
The n+1st column contains the elements of the array

Previously, the number of dimensions of an array was in a for loop, but it can be output without
Is there any convenient way?

r array

2022-09-30 20:22

2 Answers

For example, if there was such an array,

>a<-array(1:30,c(3,5,2))#3D array with size 3 x 5 x 2
>a
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    4    7   10   13
[2,]    2    5    8   11   14
[3,]    3    6    9   12   15

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]   16   19   22   25   28
[2,]   17   20   23   26   29
[3,]   18   21   24   27   30

You can use the expand.grid() function to create data frames for the index.

>indexes<-expand.grid (1:3, 1:5, 1:2)
>result<-cbind(indexes, as.vector(a))
>head(result)
  Var1 Var2 Var3 as.vector(a)
1    1    1    1            1
2    2    1    1            2
3    3    1    1            3
4    1    2    1            4
5    2    2    1            5
6    3    2    1            6

Based on this concept, if you expand it to fit any size of N-dimensional array, you'll see something like this.

>cbind(do.call(expand.grid,lapply(dim(a),seq_len))), as.vector(a))

Or

>library(dplyr)
>lapply(dim(a), seq_len)%>%do.call(expand.grid,.)%>%cbind(as.vector(a))


2022-09-30 20:22

The following is how to use as.data.frame.table().

>arr<-array(1:24, dim=c(3,4,2)))
>arr
, , 1

     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

, , 2

     [,1] [,2] [,3] [,4]
[1,]   13   16   19   22
[2,]   14   17   20   23
[3,]   15   18   21   24

>df<-as.data.frame.table(arr,base=list(as.character(1:max(dim(arr))))), responseName='value')
>df
   Var1 Var2 Var3 value
1     1    1    1     1
2     2    1    1     2
3     3    1    1     3
4     1    2    1     4
5     2    2    1     5
6     3    2    1     6
7     1    3    1     7
8     2    3    1     8
9     3    3    1     9
10    1    4    1    10
11    2    4    1    11
12    3    4    1    12
13    1    1    2    13
14    2    1    2    14
15    3    1    2    15
16    1    2    2    16
17    2    2    2    17
18    3    2    2    18
19    1    3    2    19
20    2    3    2    20
21    3    3    2    21
22    1    4    2    22
23    2    4    2    23
24    3    4    2    24


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.