我必须计算其父级 3 类别的 4 级类别价值份额。 这是我的数据框的示例: 级别由类别列中每个名称开头的代码给出,例如:“01 abc”是级别 1,“01.01.01.00 abc”是级别 4
df <- data.frame(Store = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B",
"B", "B", "B", "B", "B", "B"),
Category = c("01 Fruits & Vegetables", "01.01 Vegetables", "01.01.03 Carrots", "01.01.03.00 Baby Carrots",
"01.01.03.01 Purple Carrots", "01.01.03.01 Sliced Carrots", "01.01.05 Spinach",
"01.01.05.00 Cubes Packed", "01.01.05.01 Choped", "01.01.05.02 Leafs",
"01 Fruits & Vegetables", "01.01 Vegetables", "01.01.03 Carrots",
"01.01.03.00 Baby Carrots", "01.01.03.01 Purple Carrots", "01.01.03.01 Sliced Carrots",
"01.01.05 Spinach", "01.01.05.00 Cubes Packed", "01.01.05.01 Choped",
"01.01.05.02 Leafs"),
Value = c(1092030, 519696, 123991,
2116, 8087, 33946, 43059, 7410,
41, 24411, 1289392, 654442, 140990,
11351, 2235, 48679, 64681, 9553,
2921, 36109),
Level = c(1,2,3,4,4,4,3,4,4,4))
> df
Store Category Value Level
1 A 01 Fruits & Vegetables 1092030 1
2 A 01.01 Vegetables 519696 2
3 A 01.01.03 Carrots 123991 3
4 A 01.01.03.00 Baby Carrots 2116 4
5 A 01.01.03.01 Purple Carrots 8087 4
6 A 01.01.03.01 Sliced Carrots 33946 4
7 A 01.01.05 Spinach 43059 3
8 A 01.01.05.00 Cubes Packed 7410 4
9 A 01.01.05.01 Choped 41 4
10 A 01.01.05.02 Leafs 24411 4
11 B 01 Fruits & Vegetables 1289392 1
12 B 01.01 Vegetables 654442 2
13 B 01.01.03 Carrots 140990 3
14 B 01.01.03.00 Baby Carrots 11351 4
15 B 01.01.03.01 Purple Carrots 2235 4
16 B 01.01.03.01 Sliced Carrots 48679 4
17 B 01.01.05 Spinach 64681 3
18 B 01.01.05.00 Cubes Packed 9553 4
19 B 01.01.05.01 Choped 2921 4
20 B 01.01.05.02 Leafs 36109 4
编辑: 到目前为止,我已经尝试了以下代码,但价值共享是完全错误的。 我希望每个 4 级类别在其相应的 3 级类别(父级)中的价值份额仅适用于 3 级中的 4 级,并且对于 1:3 级只输入 0 或 100 或为空
dt1<-df %>%
mutate(Level3_Category = ifelse(Level == 3, Category,
gsub("(^\\d{2}\\.\\d{2})(\\..*)?", "\\1", Category, perl = TRUE))) %>%
group_by(Store, Category, Level3_Category) %>%
summarise(Value = sum(Value)) %>%
group_by(Level3_Category) %>%
mutate(share_percentage = Value / sum(Value) * 100)
我想要的结果示例:
商店 | 类别 | 价值 | 等级 | 价值份额 % |
---|---|---|---|---|
A | 01 水果蔬菜 | 1092030 | 1 | 100 |
A | 01.01 蔬菜 | 519696 | 2 | 100 |
A | 01.01.03 胡萝卜 | 123991 | 3 | 100 |
A | 01.01.03.00 小胡萝卜 | 2116 | 4 | 1,70 |
A | 01.01.03.01 紫色胡萝卜 | 8087 | 4 | 6,52 |
A | 01.01.03.01 胡萝卜片 | 33946 | 4 | 27,37 |