你可以使用santoku::chop_equally():
library(santoku)
chopped <- santoku::chop_equally(x, 3, labels = c("low", "medium", "high"))
data.frame(x, chopped)
x chopped
1 0.9000000 low
2 1.2666667 medium
3 4.0000000 high
4 5.7333333 high
5 19.7333333 high
6 35.7666667 high
7 44.0000000 high
8 4.4333333 high
9 0.4666667 low
10 0.7000000 low
...
然后你可以重新组合这个因素(如果你想保留低/中/高版本):
library(forcats)
chopped2 <- forcats::fct_collapse(chopped,
"High" = "high",
other_level = "Not high"
)
data.frame(x, chopped2)
x chopped2
1 0.9000000 Not high
2 1.2666667 Not high
3 4.0000000 High
4 5.7333333 High
5 19.7333333 High
6 35.7666667 High
7 44.0000000 High
8 4.4333333 High
9 0.4666667 Not high
10 0.7000000 Not high
...
或者,如果您只想要“高”/“不高”版本,请使用
chop_quantiles():
chopped2 <- santoku::chop_quantiles(x, .66,
labels = c("Not high", "High"))
data.frame(x, chopped2)
x chopped2
1 0.9000000 Not high
2 1.2666667 Not high
3 4.0000000 High
4 5.7333333 High
5 19.7333333 High
6 35.7666667 High
7 44.0000000 High
8 4.4333333 High
9 0.4666667 Not high
10 0.7000000 Not high
...
你说你想按“宽度(相等数量的值)”进行分类。上述 bins 的值数量相等,即 3 个类别中每个类别的 1/3。如果你想按宽度分箱,即等宽间隔,使用santoku::chop_evenly():
chopped3 <- santoku::chop_evenly(x, 3, labels = c("low", "medium", "high"))
data.frame(x, chopped3)
x chopped3
1 0.9000000 low
2 1.2666667 low
3 4.0000000 low
4 5.7333333 low
5 19.7333333 medium
6 35.7666667 high
7 44.0000000 high
8 4.4333333 low
9 0.4666667 low
10 0.7000000 low
...
注意:我是 santoku 包的维护者。