如何将数据帧转换为行和列中具有组值的矩阵? [英] How to transform a data frame into a matrix with group values in rows and columns?
本文介绍了如何将数据帧转换为行和列中具有组值的矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我运行了一段这样的代码
I ran a piece of code like this
x = data.frame(numerator = 1:3, value = letters[1:3],value1=letters[4:6])
xa = aggregate(list(x$numerator),by=list(x$value,x$value1),FUN=sum)
但是结果xa
的格式如下
Group.1 Group.2 X1.3
1 a d 1
2 b e 2
3 c f 3
我希望我的结果以矩阵格式进行组织,以使行由Group.1值表示,而列由Group.2值表示,如下所示:
I would like my results to be organised in a matrix format such that the rows are represented by the Group.1 values and the columns are represented by the Group.2 values, like the following:
d e f
a 1 NULL NULL
b NULL 2 NULL
c NULL NULL 3
我该怎么做?
推荐答案
您可以从plyr包中使用daply.
You can use daply from plyr package.
xa = daply(.data=x,
.variables=c("value","value1"),
.fun=function(x) sum(x$numerator))
这篇关于如何将数据帧转换为行和列中具有组值的矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文