R:根据汇总的data.frame创建条形图 [英] 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
我想绘制一个(最多)52条(每周一次)的条形图,并以每年严重"高度的堆叠条形表示.我从"barplot"文档中看到,我需要一个矩阵.当然,我可以使用for/while和smth这样的东西来获取所需的东西,但是我想知道是否没有更"R-ish"的方式来解决这个问题(看似非常典型的任务)?
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) ?
因此,用更多技术术语来说,我需要转换{X; 3}维数据帧到{52; Y}维矩阵,其中年"和周"的严重性"值将放置在适当的单元格"中.
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.
有什么想法吗?谢谢!
推荐答案
我曾经使用过一种"xtabs"方法,它的工作原理就像一个魅力:
I, for one, used an "xtabs" approach and it works like a charm:
m <- xtabs(Severity~year+month, data=ss1)
和结果:
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构建为"barplot(m)"
Barplot is then build as just "barplot(m)"
这篇关于R:根据汇总的data.frame创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!