R: Create barplot from aggregated data.frame

五迷三道 提交于 2019-12-11 10:50:33

问题


I have a result of "aggregate" like this:

   week year Severity
1    10 2013       26
2    11 2013        5
3    16 2013       26

I would like to draw a barplot with (as maximum) 52 bars (one for every week) with stacked bars of "severity" height for every year. I see from "barplot" documentation that I need a matrix for that. Of course I could use for/while and smth like that to get what I need, but I wonder if there's not a more "R-ish" way to solve this (seemingly pretty typical task) ?

So, in more technical terms, I need to convert my {X; 3} dimensional data frame to a {52; Y} dimensional matrix, where values of "severity" for "year" and "week" will be placed into proper "cells".

I've tried to use "melt" but the only difference I see is a change in column names + extra column.

Any ideas? Thanks !


回答1:


Apparently, this was already answered in Reshape three column data frame to matrix ("long" to "wide" format)

I, for one, used an "xtabs" approach and it works like a charm:

m <- xtabs(Severity~year+month, data=ss1)

and the result:

      month
year    1  2  3  4  5  8  9 10 11 12
  2013  0  0 31 32 26 17  0 33  0 40
  2014  0  0 22 33 22  0  8  0 57  6
  2015 23  2  0  0 32  0 26  0  0  0
  2016  0 28  0  0  0  0  0  0  0  0

Barplot is then build as just "barplot(m)"



来源:https://stackoverflow.com/questions/36135900/r-create-barplot-from-aggregated-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!