How to get data.frame in multidimensional array in R?

I am looking for a more universal way to get a multidimensional array from data.frame.

I would like to be able to create as many dimensions as needed from the number of variables in the data frame as I wish.

Currently, the method must be adapted to each data.frame file; it requires subclasses to form a vector.

I would like something using the melt / cast method in plyr.

data<-data.frame(coord.name=rep(1:10, 2), x=rnorm(20), y=rnorm(20), ID=rep(c("A","B"), each=10)) data.array<-array(dim=c(10, 2, length(unique(data$ID)))) for(i in 1:length(unique(data$ID))){ data.array[,1,i]<-data[data$ID==unique(data$ID)[i],"x"] data.array[,2,i]<-data[data$ID==unique(data$ID)[i],"y"] } data.array , , 1 [,1] [,2] [1,] 1 1 [2,] 3 3 [3,] 5 5 [4,] 7 7 [5,] 9 9 [6,] 1 1 [7,] 3 3 [8,] 5 5 [9,] 7 7 [10,] 9 9 , , 2 [,1] [,2] [1,] 2 2 [2,] 4 4 [3,] 6 6 [4,] 8 8 [5,] 10 10 [6,] 2 2 [7,] 4 4 [8,] 6 6 [9,] 8 8 [10,] 10 10 
+6
source share
2 answers

You may be having problems using reshape2 functions for some subtle reason. The difficulty was that your data.frame does not have a column that can be used to indicate how you want to arrange the elements by the first size of the output array.

Below I explicitly add such a column, calling it "row" . With it, you can use the expressive functions acast() or dcast() to modify data in any way.

 library(reshape2) # Use this or some other method to add a column of row indices. data$row <- with(data, ave(ID==ID, ID, FUN = cumsum)) m <- melt(data, id.vars = c("row", "ID")) a <- acast(m, row ~ variable ~ ID) a[1:3, , ] # , , A # # xy # 1 1 1 # 2 3 3 # 3 5 5 # # , , B # # xy # 1 2 2 # 2 4 4 # 3 6 6 
+7
source

I think this is correct:

 array(unlist(lapply(split(data, data$ID), function(x) as.matrix(x[ , c("x", "y")]))), c(10, 2, 2)) 
+4
source

Source: https://habr.com/ru/post/912544/


All Articles