我试图像这样转换我的数据
"Months 2005 2006 2007 2008 2009 2010"
Jan 28.1 5.8 22.9 64.2 70.1 85.9
Feb 41.4 85.1 149.2 31.0 142.1 36.9
Mar 153.2 145.9 101.6 308.8 171.8 57.5
Apr 57.0 212.4 170.3 244.5 278.9 132.9
May 154.9 119.9 57.8 128.8 212.7 55.6
jun 158.6 81.3 160.8 94.0 115.3 63.3
Jul 22.6 27.2 29.4 80.9 82.7 30.9
我目前的数据(约6个站点:ABCDEF)看起来像这样的格式:
station element Year Month
1 A 41.4 2005 1
2 B 158.6 2005 2
3 C 23 2006 3
4 D 234 2007 4
5 E 0 2010 5
6 F 0 2010 6
答案 0 :(得分:2)
听起来就像你说的那样,你想要从底层数据结构转到顶层数据结构。如果是这种情况,您可以尝试xtabs
(如果sum
是您需要作为聚合函数的所有内容)或dcast
来自" reshape2" :
library(reshape2)
dcast(mydf, Month ~ Year, value.var="element", fun.aggregate=sum)
# Month 2005 2006 2007 2010
# 1 1 41.4 0 0 0
# 2 2 158.6 0 0 0
# 3 3 0.0 23 0 0
# 4 4 0.0 0 234 0
# 5 5 0.0 0 0 0
# 6 6 0.0 0 0 0
xtabs(element ~ Month + Year, mydf)
# Year
# Month 2005 2006 2007 2010
# 1 41.4 0.0 0.0 0.0
# 2 158.6 0.0 0.0 0.0
# 3 0.0 23.0 0.0 0.0
# 4 0.0 0.0 234.0 0.0
# 5 0.0 0.0 0.0 0.0
# 6 0.0 0.0 0.0 0.0
更改"月"的数值等同于短文本应该是使用[
和month.abb
的非常简单的替换活动,可以在转换数据之前或之后完成。
这假定" mydf"定义为:
mydf <- structure(list(station = c("A", "B", "C", "D", "E", "F"),
element = c(41.4, 158.6, 23, 234, 0, 0),
Year = c(2005L, 2005L, 2006L, 2007L, 2010L, 2010L),
Month = 1:6),
.Names = c("station", "element", "Year", "Month"),
class = "data.frame",
row.names = c("1", "2", "3", "4", "5", "6"))