如何将数据框转换为 R 中的 3d 数组 [英] How to convert a data frame to a 3d array in R

查看:22
本文介绍了如何将数据框转换为 R 中的 3d 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要转换为三维数组的数据框.数据框中的一列应作为分组变量,用于将帧拆分为可以组合到数组中的二维矩阵.在下面的最小工作示例中,数据帧应该被变量i"分割成矩阵,然后组合成一个 4x4x2 数组.该解决方案应该适用于大型数据集,理想情况下可以推广到将数据帧转换为 n 维数组.

I have a data frame that I want to convert to a three-dimensional array. One of the columns in the data frame should serve as the grouping variable for splitting the frame into 2d matrices that can be combined into the array. In the following minimal working example, the data frame should be split into matrices by the variable "i", then combined into a 4x4x2 array. The solution should be practical for large data sets and ideally could be generalized to convert a data frame into a n dimensional array.

# Make reproducible 
set.seed(123)

df <- {
  data.frame(i=rep(1:2, each=4),
             x=rep(rep(0:1, each=2), 2),
             y=rep(rep(0:1, 2), 2),
             l=rnorm(8))
}

df
#   i x y           l
# 1 1 0 0 -0.56047565
# 2 1 0 1 -0.23017749
# 3 1 1 0  1.55870831
# 4 1 1 1  0.07050839
# 5 2 0 0  0.12928774
# 6 2 0 1  1.71506499
# 7 2 1 0  0.46091621
# 8 2 1 1 -1.26506123

注意:我怀疑 Hadley Wickham 的 plyr 可能会提供所需的工具,也许是 daply?

Note: I suspect that Hadley Wickham's plyr may provide the needed tool, perhaps daply?

推荐答案

我可能会这样做:

library(abind)
abind(split(df, df$i), along=3)
# , , 1
# 
#   i x y           l
# 5 1 0 0 -0.56047565
# 6 1 0 1 -0.23017749
# 7 1 1 0  1.55870831
# 8 1 1 1  0.07050839
# 
# , , 2
# 
#   i x y          l
# 5 2 0 0  0.1292877
# 6 2 0 1  1.7150650
# 7 2 1 0  0.4609162
# 8 2 1 1 -1.2650612

这篇关于如何将数据框转换为 R 中的 3d 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆