Boxplot of pre-aggregated/grouped data in R

余生颓废 提交于 2019-12-10 13:14:43

问题


In R I want to create a boxplot over count data instead of raw data. So my table schema looks like

Value | Count
1 | 2
2 | 1

...

Instead of

Value
1
1
2
...

Where in the second case I could simply do boxplot(x)


回答1:


I'm sure there's a way to do what you want with the already summarized data, but if not, you can abuse the fact that rep takes vectors:

> dat <- data.frame(Value = 1:5, Count = sample.int(5))
> dat
  Value Count
1     1     1
2     2     3
3     3     4
4     4     2
5     5     5
> rep(dat$Value, dat$Count)
 [1] 1 2 2 2 3 3 3 3 4 4 5 5 5 5 5

Simply wrap boxplot around that and you should get what you want. I'm sure there's a more efficient / better way to do that, but this should work for you.




回答2:


I solved a similar issue recently by using the 'apply' function on each column of counts with the 'rep' function:

> datablock <- apply(countblock[-1], 2, function(x){rep(countblock$value, x)})
> boxplot(datablock)

...The above assumes that your values are in the first column and subsequent columns contain count data.




回答3:


A combination of rep and data.frame can be used as an approach if another variable is needed for classification

Eg.

with(data.frame(v1=rep(data$v1,data$count),v2=(data$v2,data$count)),
    boxplot(v1 ~ v2)
)




回答4:


Toy data:

(besides Value and Count, I add a categorical variable Group)

set.seed(12345)
df <- data.frame(Value = sample(1:100, 100, replace = T),
                 Count = sample(1:10, 100, replace = T),
                 Group = sample(c("A", "B", "C"), 100, replace = T),
                 stringsAsFactors = F)

Use purrr::pmap and purrr::reduce to manipulate the data frame:

library(purrr)
data <- pmap(df, function(Value, Count, Group){
  data.frame(x = rep(Value, Count),
             y = rep(Group, Count))
}) %>% reduce(rbind)

boxplot(x ~ y, data = data)



来源:https://stackoverflow.com/questions/7933268/boxplot-of-pre-aggregated-grouped-data-in-r

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