添加零值条目,以便所有组都具有相同项目的条目 [英] Adding zero valued entries so that all groups have entries for the same items

查看:30
本文介绍了添加零值条目,以便所有组都具有相同项目的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用

堆叠


数据

  df<-structure(list(Region = structure(c(3L,3L,3L,2L,2L,1L),.Label = c("France","UK","USA"),class ="factor"),Group =结构(c(1L,2L,3L,1L,2L,3L),.Label = c("A","B","C"),class ="factor"),值= c(5L,3L,1L,4L,6L,3L)),.Names = c("Region","Group","Value"),类="data.frame",row.names = c(NA,-6L)) 

I'm trying to use Rcharts to create a stacked bar chart across a number of recorded regions (stacking separate group values on top of each other). The data is in a format similar to below.

Region | Group | Value
----------------------
USA    |   A   |   5
USA    |   B   |   3
USA    |   C   |   1
UK     |   A   |   4
UK     |   B   |   6
France |   C   |   3

Using the below code produces a grouped bar chart which works fine. However the stacked button does nothing to change the plot.

nPlot(Value ~ Region, group = 'Group', 
      data = example_data, 
      type = 'multiBarChart')

Looking at this thread it seems the problem might be that some Regions don't have entries for all present groups (e.g. the UK lacks an entry for C, and France lacks entries for A and B).

What I'm not sure of is how to add entries with Value == 0 so that all Regions have an entry for every present Group. So that the above data is transformed to this (the ordering of entries doesn't matter).

Region | Group | Value
----------------------
USA    |   A   |   5
USA    |   B   |   3
USA    |   C   |   1
UK     |   A   |   4
UK     |   B   |   6
UK     |   C   |   0
France |   A   |   0
France |   B   |   0
France |   C   |   3

This will ultimately be placed within the reactive component of a Shiny app so efficient solutions in particular would be great

解决方案

We can use complete() from the tidyr package:

This is a wrapper around expand(), left_join() and replace_na that's useful for completing missing combinations of data. It turns implicitly missing values into explicitly missing values.

library(tidyr)
library(rCharts)

df %>% 
  complete(Region, Group, fill = list(Value = 0)) %>%
  nPlot(Value ~ Region, group = 'Group', 
        data = ., 
        type = 'multiBarChart')


Grouped

Stacked


Data

df <- structure(list(Region = structure(c(3L, 3L, 3L, 2L, 2L, 1L), .Label = c("France", 
"UK", "USA"), class = "factor"), Group = structure(c(1L, 2L, 
3L, 1L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
    Value = c(5L, 3L, 1L, 4L, 6L, 3L)), .Names = c("Region", 
"Group", "Value"), class = "data.frame", row.names = c(NA, -6L))

这篇关于添加零值条目,以便所有组都具有相同项目的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆