Reputation: 1022
I have the below data with date and count. Please help in transforming this one row where months are columns. And rows are data of each year
Date count
=================
2011-01-01 10578
2011-02-01 9330
2011-03-01 10686
2011-04-01 10260
2011-05-01 10032
2011-06-01 9762
2011-07-01 10308
2011-08-01 9966
2011-09-01 10146
2011-10-01 10218
2011-11-01 8826
2011-12-01 9504
to
JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
------------------------------------------------------------------------------
2011 10578 9330 10686 10260 10032 9762 10308 9966 10146 10218 8826 9504
2012 ....
Upvotes: 0
Views: 1170
Reputation: 6290
If your data is in x
try something like this:
library(reshape2)
res <- dcast(transform(x, month = format(Date, format="%m"),
year = format(Date, "%Y")),
year ~ month, value.var="count")
rownames(res) <- res$year
res <- res[,-1]
names(res) <- toupper(month.abb[as.numeric(names(res))])
res
This assumes that x$Date
is already a date. If not, you will need to first convert is to a date:
x$Date <- as.Date(x$Date)
Upvotes: 1
Reputation: 61214
This is a perfect task for ts
in R base. Suppose your data.frame is x
then using ts
will produce the output you want.
> ts(x$count, start=c(2011,01,01), end=c(2011,12,01), frequency=12)
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2011 10578 9330 10686 10260 10032 9762 10308 9966 10146 10218 8826 9504
Upvotes: 2