如何从数据框架创建矩阵? [英] How to create the matrix from data frame?
本文介绍了如何从数据框架创建矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SLP网站年
8.6 1 2008
7.2 1 2005
6.4 2 2006
9.5 3 2007
6.1 2 2009
3.6 1 2005
8.6 1 2008
7.2 1 2005
6.4 2 2006
9.5 3 2007
6.1 2 2009
5.1 3 2008
2.1 2 2006
我想要的输出是:
1 2 3
2005 6.00 - -
2006 - 4.97 -
2007 - - 9.5
2008 8.60 - 5.1
2009 - 6.10 -
列名是网站的变量,行名称是年的变量,每个单元格中的值是SLP的平均值。我该怎么做?
解决方案
我们可以使用 acast
p>
library(reshape2)
acast(df1,year〜site,value.var =SLP,mean)
或使用 c $ c>从
base R
with(df1,tapply SLP,列表(年份,网站),FUN =平均))
i have a data frame as follows, I want to create a matrix, where the average sleep duration hour (SLP) is shown according to 3 recruiting site(site) and 5 recruiting year(year).
SLP site year
8.6 1 2008
7.2 1 2005
6.4 2 2006
9.5 3 2007
6.1 2 2009
3.6 1 2005
8.6 1 2008
7.2 1 2005
6.4 2 2006
9.5 3 2007
6.1 2 2009
5.1 3 2008
2.1 2 2006
My desired output is:
1 2 3
2005 6.00 - -
2006 - 4.97 -
2007 - - 9.5
2008 8.60 - 5.1
2009 - 6.10 -
Column name is variable of site, row name is variable of year and values in each cell is average of SLP. How do I do this?
解决方案
We can use acast
library(reshape2)
acast(df1, year~site, value.var="SLP", mean)
Or using tapply
from base R
with(df1, tapply(SLP, list(year, site), FUN = mean))
这篇关于如何从数据框架创建矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文