Reputation: 17
How can I make my data frame or make a table from
TIME_PERIOD MARRIAGE_LICENSES
1 2011-01 742
2 2011-02 796
3 2011-03 1210
4 2011-04 1376
....
To something that looks like
01 02 03 04 05 06 07 08 09 10 11 11
2011 742 796 1210 1376
2012
2013
2014
2015
and so on?
Upvotes: 1
Views: 59
Reputation: 99321
You could do something like this
library(tidyr) ## for separate()
xtabs(MARRIAGE_LICENSES ~ ., separate(df, TIME_PERIOD, c("year", "month"), "-"))
# month
# year 01 02 03 04
# 2011 742 796 1210 1376
Data:
df <- structure(list(TIME_PERIOD = structure(1:4, .Label = c("2011-01",
"2011-02", "2011-03", "2011-04"), class = "factor"), MARRIAGE_LICENSES = c(742L,
796L, 1210L, 1376L)), .Names = c("TIME_PERIOD", "MARRIAGE_LICENSES"
), class = "data.frame", row.names = c("1", "2", "3", "4"))
Upvotes: 1
Reputation: 34703
You could do this with data.table
as:
library(data.table)
setDT(dat)
dcast(dat, format(TIME_PERIOD, "%Y") ~ format(TIME_PERIOD, "%m"),
value.var = "MARRIAGE_LICENSES")
(note: requires MARRIAGE_LICENSE
to be stored as a Date
or other object which has an appropriate format
method first)
Upvotes: 2
Reputation: 21497
Using reshape2
you can do the following (which gives you a data.frame
)
require(reshape2)
dat$year <- as.numeric(substr(dat$TIME_PERIOD,1,4))
dat$month <- as.numeric(substr(dat$TIME_PERIOD,6,8))
require(reshape2)
dcast(dat, year~month, value.var = "MARRIAGE_LICENSES")
This gives you
year 1 2 3 4
1 2011 742 796 1210 1376
If you want to have your format and the years as rownames do:
df <- dcast(dat, year~month, value.var = "MARRIAGE_LICENSES")
rownames(df) <- df$year
df[,-1]
Resulting in
1 2 3 4
2011 742 796 1210 1376
Upvotes: 1