如何制作数据框或从
制作表格 TIME_PERIOD MARRIAGE_LICENSES
1 2011-01 742
2 2011-02 796
3 2011-03 1210
4 2011-04 1376
....
看起来像
的东西 01 02 03 04 05 06 07 08 09 10 11 11
2011 742 796 1210 1376
2012
2013
2014
2015
等等?
答案 0 :(得分:2)
您可以使用data.table
执行此操作:
library(data.table)
setDT(dat)
dcast(dat, format(TIME_PERIOD, "%Y") ~ format(TIME_PERIOD, "%m"),
value.var = "MARRIAGE_LICENSES")
(注意:要求MARRIAGE_LICENSE
存储为Date
或其他具有适当format
方法的对象
答案 1 :(得分:1)
使用reshape2
,您可以执行以下操作(这会为您提供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")
这会给你
year 1 2 3 4
1 2011 742 796 1210 1376
如果您希望将您的格式和年份作为rownames:
df <- dcast(dat, year~month, value.var = "MARRIAGE_LICENSES")
rownames(df) <- df$year
df[,-1]
导致
1 2 3 4
2011 742 796 1210 1376
答案 2 :(得分:1)
你可以做这样的事情
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
数据:强>
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"))