我有这个df:
structure(list(YEAR = c("2007", "2007", "2007", "2008", "2008",
"2008", "2008", "2008", "2008", "2008"), MONTH = c("12", "10",
"11", "01", "03", "05", "06", "08", "09", "10"), TOTAL = c(85055988L,
21567576L, 82763640L, 91007916L, 93936288L, 99646750L, 90091044L,
98811936L, 96888876L, 100909236L)), .Names = c("YEAR", "MONTH",
"TOTAL"), row.names = c("24801", "33863", "34055", "24973", "25046",
"25295", "25384", "25541", "25861", "27319"), class = "data.frame")
我想按如下方式组织这个数据框:
YEAR JAN FEB MARCH .... DEC
2009 TOTAL VALUE FOR EACH month goes to each corresponding cells.
我是如何在R中轻松完成此任务的?
答案 0 :(得分:1)
dcast
和xtabs
是需要考虑的选项之一:
xtabs(TOTAL ~ YEAR + MONTH, df)
# MONTH
# YEAR 01 03 05 06 08 09 10 11 12
# 2007 0 0 0 0 0 0 21567576 82763640 85055988
# 2008 91007916 93936288 99646750 90091044 98811936 96888876 100909236 0 0
library(reshape2)
dcast(df, YEAR ~ MONTH, value.var="TOTAL", fun.aggregate=sum)
# YEAR 01 03 05 06 08 09 10 11 12
# 1 2007 0 0 0 0 0 0 21567576 82763640 85055988
# 2 2008 91007916 93936288 99646750 90091044 98811936 96888876 100909236 0 0