让我们假设下面这样的数据
ID Quantity Group Indicator
1 0.93 Red 1
2 0.17 Red 1
3 0.01 Red 0
4 0.44 Red 1
5 0.01 Red 0
6 0.86 Red 1
7 0.07 Red 1
8 0.02 Red 0
9 1.00 Red 1
1 0.65 Blue 1
2 0.17 Blue 1
3 0.02 Blue 0
4 0.01 Blue 0
5 0.09 Blue 1
6 0.86 Blue 1
7 0.05 Blue 0
8 0.23 Blue 1
9 0.01 Blue 0
现在,我想创建一个具有三个值/类别的新列.
- 如果指标列值为0,则为1
- 3如果指标列值为1,且列数量中的值等于或高于中位数(指标==1的所有值的数量的中位数).
- 2如果指标列值为1,且列数量中的值等于或低于中位数(指标==1的所有值的数量的中位数).
此逻辑将分别应用于组中的值.
预计会有这样的输出.
红色组中所有数量值的中位数,其中指标==1. 中位数(0.93,0.17,0.44,0.86,0.07,1.00)=0.65
蓝色组中所有数量值的中位数,其中指标==1. 中位数(0.65,0.17,0.09,0.86,0.23)=0.23
ID Quantity Group Indicator Results
1 0.93 Red 1 3 <- Above the median(0.65) for all values in red where Indicator ==1
2 0.17 Red 1 2 <- Below the median(0.65) for all values in red where Indicator ==1
3 0.01 Red 0 1
4 0.44 Red 1 2 <- Below the median(0.65) for all values in red where Indicator ==1
5 0.01 Red 0 1
6 0.86 Red 1 3 <- Above the median(0.65) for all values in red where Indicator ==1
7 0.07 Red 1 2 <- Below the median(0.65) for all values in red where Indicator ==1
8 0.02 Red 0 1
9 1.00 Red 1 3 <- Above the median(0.65) for all values in red where Indicator ==1
1 0.65 Blue 1 3
2 0.17 Blue 1 2
3 0.02 Blue 0 1
4 0.01 Blue 0 1
5 0.09 Blue 1 2
6 0.86 Blue 1 3
7 0.05 Blue 0 1
8 0.23 Blue 1 2
9 0.01 Blue 0 1
我已经用很多If试过了,它非常笨拙.寻找使用Case_When的有效内容.先谢谢你.