1

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 !

62mkv
  • 1,444
  • 1
  • 16
  • 28
  • Can you `paste` the first two columns together to form a week-year ID which has 52 unique combinations? Then plot a bar graph with week-year as x-axis and Severity as y-axis as normal. – Heisenberg Mar 21 '16 at 16:01
  • I am not sure I have completely understood this.. "week+year" would definitely NOT give 52 unique values... as I have data for several years (should have to mention it explicitly, my bad...) – 62mkv Mar 22 '16 at 15:31
  • I don't know where the 52 comes from, but if you have one observation per week then week + year would be a unique combination. If not then you need to post more representative data. – Heisenberg Mar 22 '16 at 15:47
  • I have already found the answer, thank you very much for attention! – 62mkv Mar 22 '16 at 16:13

1 Answers1

0

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)"

Community
  • 1
  • 1
62mkv
  • 1,444
  • 1
  • 16
  • 28