Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Convert 3D array into list of dataframes

$
0
0

Basically, I want to group a 3D array by its columns, transform it into a data frame, and bind to it a new column whose value equals to the sum of all existing columns.

For example, consider the following 3D array

> (src <- array(1:8, c(2, 2, 2), dimnames=list(c('X1', 'X2'), c('Y1', 'Y2'), 1:2)))
, , 1

   Y1 Y2
X1  1  3
X2  2  4

, , 2

   Y1 Y2
X1  5  7
X2  6  8

I would like to convert it to

> (dest <- list(Y1=data.frame(X1=c(1, 5), X2=c(2, 6), Y1=c(1, 5)+c(2, 6)),
                Y2=data.frame(X1=c(3, 7), X2=c(4, 8), Y2=c(3, 7)+c(4, 8))))
$Y1
  X1 X2 Y1
1  1  2  3
2  5  6 11

$Y2
  X1 X2 Y2
1  3  4  7
2  7  8 15

I know how to do the transformation for each individual column in the original array, but have no idea how to handle multiple columns simultaneously.

> library(dplyr)
> as.data.frame(t(src[, 'Y1', ])) %>% mutate(Y1=X1+X2)
  X1 X2 Y1
1  1  2  3
2  5  6 11

Feel free to use base R, dplyr, data.table, or whatever package you prefer, as long as it's fast enough. In the real-world application, dim(src) tend to be something like c(hundreds, tens, tens of thousands).


Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>