将数据帧强制转换为具有多个组的矩阵

时间:2014-07-18 15:10:46

标签: r matrix

我想知道以下内容的等价物,但当我有多个相同类型的数据时。

示例A:为了将我的数据转换为旋转矩阵形式,我可以使用强制转换函数,即

birthday_week   current_week    variable
26/03/2012  26/03/2012  100
26/03/2012  02/04/2012  125
02/04/2012  26/03/2012  50
02/04/2012  02/04/2012  10

此功能:

as.matrix(cast(data,birthday_week ~current_week,value='variable'))      

会给出这个结果:

    26/03/2012  02/04/2012
26/03/2012  100 125
02/04/2012  50  10

但是,我的实际数据有几个组,即

    birthday_week   current_week    variable
group1  26/03/2012  26/03/2012  100
group1  26/03/2012  02/04/2012  125
group1  02/04/2012  26/03/2012  50
group1  02/04/2012  02/04/2012  10
group2  26/03/2012  26/03/2012  10
group2  26/03/2012  02/04/2012  15
group2  02/04/2012  26/03/2012  20
group2  02/04/2012  02/04/2012  10

将它放入带有矩阵的列表对象的最佳方法是什么,即

$group1
        26/03/2012  02/04/2012
    26/03/2012  100 125
    02/04/2012  50  10

$group2 
        26/03/2012  02/04/2012
    26/03/2012  10  15
    02/04/2012  20  10

1 个答案:

答案 0 :(得分:1)

你真的很亲密:

library(reshape2)
lapply(split(df,df$group),
       function(df)acast(df,birthday_week~current_week,value.var="variable"))
# $group1
#            02/04/2012 26/03/2012
# 02/04/2012         10         50
# 26/03/2012        125        100
# 
# $group2
#            02/04/2012 26/03/2012
# 02/04/2012         10         20
# 26/03/2012         15         10

这假设您的数据框名为df,并且列group包含分组变量。