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?
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))
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
610 Uncaught (inpromise) Error on Electron: An object could not be cloned
567 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
600 GDB gets version error when attempting to debug with the Presense SDK (IDE)
887 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.