It sounds like you're saying you want to go from the bottom data structure to the top one. If that's the case, you can try xtabs
(if sum
is all that you would need as an aggregation function) or dcast
from "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
Changing the numeric value of "Month" to the short text equivalent should be a pretty straightforward substitution activity using [
and month.abb
and can be done before or after transforming the data.
This assumes that "mydf" is defined as:
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"))