如何将data.frame放入R中的多维数组中?

如何将data.frame放入R中的多维数组中?,r,dataframe,plyr,R,Dataframe,Plyr,我正在寻找一种从data.frame到多维数组的更通用的方法 我希望能够根据需要从数据框架中的任意多个变量创建任意多个维度 目前,该方法必须针对每个数据帧进行定制,需要分包以形成向量 我很喜欢plyr的熔化/铸造方法 data<-data.frame(coord.name=rep(1:10, 2), x=rnorm(20), y=rnorm(20), ID=rep(c("A","B"), each=10))

我正在寻找一种从data.frame到多维数组的更通用的方法

我希望能够根据需要从数据框架中的任意多个变量创建任意多个维度

目前,该方法必须针对每个数据帧进行定制,需要分包以形成向量

我很喜欢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

数据我认为这是对的:

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

由于某种微妙的原因,您可能无法应用重塑2函数。困难在于data.frame没有可用于指示如何沿输出数组的第一维度排列元素的列

下面,我明确地添加了这样一个列,称之为
“row”
。有了它,您可以使用expressive
acast()
dcast()
函数以您选择的任何方式重塑数据

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
# 
#   x y
# 1 1 1
# 2 3 3
# 3 5 5
#
# , , B
# 
#   x y
# 1 2 2
# 2 4 4
# 3 6 6
library(重塑2)
#使用此方法或其他方法添加行索引列。

数据$row…您是否总是有两个数字列,然后是零个或多个因子列?