2

Suppose I have the dataset

ID Country Sales
1 Austria 6
1 Austria 6
1 Belgium 6
2 Belgium 10
2 Czech 10
3 Denmark 3
3 Germany 3

I want to another variable of sales which depends on countries and their ID ie in fractions.

ID Country Sales fraction
1 Austria 6 0.666
1 Austria 6 0.666
1 Belgium 6 0.333
2 Belgium 10 0.5
2 Czech 10 0.5
3 Denmark 3 1
3 Denmark 3 1

Any help would be appreciated!

3 Answers3

1
library(dplyr)
your_data |>
  mutate(country_total = sum(Sales), .by = c(ID, Country)) |>
  mutate(fraction = country_total / sum(Sales), .by = ID)
#   ID Country Sales country_total  fraction
# 1  1 Austria     6            12 0.6666667
# 2  1 Austria     6            12 0.6666667
# 3  1 Belgium     6             6 0.3333333
# 4  2 Belgium    10            10 0.5000000
# 5  2   Czech    10            10 0.5000000
# 6  3 Denmark     3             3 0.5000000
# 7  3 Germany     3             3 0.5000000

Using this sample data:

your_data = read.table(text = 'ID   Country     Sales
1   Austria     6
1   Austria     6
1   Belgium     6
2   Belgium     10
2   Czech   10
3   Denmark     3
3   Germany     3', header = T)
Julian
  • 6,586
  • 2
  • 9
  • 33
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

Alternatively we could use add_count to get the same result

library(dplyr)

df %>% add_count(ID,name = 'n') %>% add_count(ID,Country, name = 'gn') %>% 
mutate(new=gn/n) %>% select(-c(n,gn))

# output

# A tibble: 7 × 4
     ID Country Sales   new
  <dbl> <chr>   <dbl> <dbl>
1     1 Austria     6 0.667
2     1 Austria     6 0.667
3     1 Belgium     6 0.333
4     2 Belgium    10 0.5  
5     2 Czech      10 0.5  
6     3 Denmark     3 0.5  
7     3 Germany     3 0.5  
```
jkatam
  • 2,691
  • 1
  • 4
  • 12
0

Base

> df$fraction=ave(df$Sales,list(df$ID,df$Country),FUN=sum)/ave(df$Sales,df$ID,FUN=sum)

  ID Country Sales  fraction
1  1 Austria     6 0.6666667
2  1 Austria     6 0.6666667
3  1 Belgium     6 0.3333333
4  2 Belgium    10 0.5000000
5  2   Czech    10 0.5000000
6  3 Denmark     3 0.5000000
7  3 Germany     3 0.5000000
user2974951
  • 9,535
  • 1
  • 17
  • 24