简体   繁体   中英

R: Create barplot from aggregated data.frame

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM