如何在R中将data.frame转换为多维数组?

7
我想找一个更通用的方法将数据框转换成多维数组。
我希望能够根据需要从数据框中的任意变量创建所需数量的维度。
目前,该方法必须针对每个数据框进行定制,并需要子集来形成向量。
我希望有类似于plyr中的melt / cast方法的东西。
   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

你是否总是有两个数字列,然后是零个或多个因子列? - Tommy
2个回答

7
你可能在使用reshape2函数时遇到了一些麻烦,原因可能有点微妙。问题在于你的数据框中没有一列可以用来指导如何排列输出数组的元素。

下面,我会明确地添加这样一列,并将其称为"row"。有了它,你就可以使用具有表现力的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

4

我认为这是正确的:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接