我会使用cut 函数来做你正在做的事情。之后,您可以使用fct_collapse 修改您的切割点。您可以执行以下操作:
library(dplyr)
library(forcats)
library(ggplot2)
iris %>%
filter(Species == "setosa") %>%
mutate(sub_species = cut(Sepal.Length, breaks = c(-Inf, 4.7, 5, 5.2, Inf))) %>%
mutate(sub_species = fct_collapse(sub_species,
combined = c("(-Inf,4.7]", "(5.2, Inf]"))) %>%
ggplot(aes(sub_species, Petal.Length))+
geom_boxplot()
这会给你想要的。
或者,您可以替换 cut 函数并使用 dplyr 的情况,当函数看起来像:
iris %>%
filter(Species == "setosa") %>%
# Case when to cases
mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
Sepal.Length < 5~ "B",
Sepal.Length < 5.2~ "C",
TRUE~"D")) %>%
# Collapse A and D
mutate(collapsed = ifelse(sub_a %in% c("A", "D"), "combined", sub_a)) %>%
ggplot(aes(collapsed, Petal.Length))+
geom_boxplot()
在 OP 评论中,问题被扩展为包括创建其他几个子类。为了解决这个问题,我将使用mutate 函数创建一些额外的子类别,然后使用gather 函数将它们全部拉到一个列中,同时保留每个子类中的数据(例如保持计数正确)。
iris %>%
filter(Species == "setosa") %>%
# Case when to cases
mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
Sepal.Length < 5~ "B",
Sepal.Length < 5.2~ "C",
TRUE~"D")) %>%
# Collapse A and D
mutate(collapsed1 = ifelse(sub_a %in% c("A", "C"), "A+C", sub_a)) %>%
mutate(collapsed2 = ifelse(sub_a %in% c("A", "C", "D"), "A+C+D", sub_a)) %>%
# Pull all the new categories together into a new column called subclass
gather(new_cat, subclass, sub_a:collapsed2) %>%
# Filter to desired
filter(subclass %in% c("B", "A+C", "D", "A+C+D")) %>%
ggplot(aes(subclass, Petal.Length))+
geom_boxplot()