0

I would like calculate value share of each class in each store. Is that possibe inside a mutate?

data<-read_excel("data.xlsx")

data2<-data%>%
  group_by(Store, Class)%>%
  summarise(Values=sum(Value))%>%
  mutate(Values2=Valor/???)

I have a dataset like this:

    Store   Class   Value
    A   1   100
    A   2   200
    A   3   300
    A   1   200
    A   2   400
    A   3   600
    B   1   10
    B   2   20
    B   3   30
    B   1   20
    B   2   40
    B   3   60

Thanks!

  • 1
    library(dplyr) df %>% group_by(Store, Class) %>% mutate(share = Value / sum(Value)) Do you mean this? Or could you please make clear what you mean with value share? – Lennyy Jun 15 '18 at 13:57
  • Welcome to SO. Please have a look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example It will be better if you share part of `data` and expected output along with question. Please add output of `dput(head(data,20))` in question. – MKR Jun 15 '18 at 14:21

1 Answers1

0

After grouping the data frame, you can sum your values column twice and see that operation behave differently: Inside summarise, it will add up all the values for each combination of store and class. Then in the mutate in the next line, it will assume you're stripping away the second layer of grouping (in this case, class), and give you sums by store. So then mutate(share = Value / sum(Value)) yields the share with respect to the store, for each class.

library(dplyr)

df <- "Store   Class   Value
    A   1   100
A   2   200
A   3   300
A   1   200
A   2   400
A   3   600
B   1   10
B   2   20
B   3   30
B   1   20
B   2   40
B   3   60" %>% readr::read_table2()

df %>%
  group_by(Store, Class) %>%
  summarise(Value = sum(Value)) %>%
  mutate(share = Value / sum(Value))
#> # A tibble: 6 x 4
#> # Groups:   Store [2]
#>   Store Class Value share
#>   <chr> <int> <int> <dbl>
#> 1 A         1   300 0.167
#> 2 A         2   600 0.333
#> 3 A         3   900 0.5  
#> 4 B         1    30 0.167
#> 5 B         2    60 0.333
#> 6 B         3    90 0.5

Created on 2018-06-15 by the reprex package (v0.2.0).

camille
  • 16,432
  • 18
  • 38
  • 60