如何在 R 中存在公式的情况下绘制子组

How to boxplot a subgroup in presence of the formula in R

nor this post 都不适用于我的情况。

假设:

set.seed(42)
x<-rep(c("A","B","C"), c(3,4,1))
y<-rep(c("V","W"),c(5,3))
z<-rnorm(8,-2,1)
df<-data.frame(x,y,z)
boxplot(z~x+y,df)

我希望我的情节包括具有多个元素的组,比方说,一个元素。这意味着我希望我的情节只显示 A.V、B.V 和 B.W。 此外,由于我的图表有大约 70 个组,我不想通过手写列表来完成。

谢谢

您可以使用 paste 创建新列 ('xy'),使用 ave 为具有多个元素的 'xy' 组创建逻辑索引,然后做 boxplot.

df1$xy <- factor(paste(df1$x, df1$y, sep='.'))
index <-  with(df1, ave(1:nrow(df1), xy, FUN=length))>1
boxplot(z~xy, droplevels(df1[index,]))

或使用ggplot

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
   group_by(x,y) %>%
   filter(n()>1) %>%
   unite(xy, x,y) %>% 
   ggplot(., aes(xy, z))+
                geom_boxplot()

您可以查看是否有任何 bp$n 为 0 并由其子集

set.seed(42)
df <- data.frame(x = rep(c("A","B","C"), c(3,4,1)),
                 y = rep(c("V","W"),c(5,3)),
                 z = rnorm(8,-2,1))
bp <- boxplot(z ~ x + y, df, plot = FALSE)
wh <- which(bp$n == 0)

bp[] <- lapply(bp, function(x) if (length(x)) {
  ## `bp` contains a list of boxplot statistics, some vectors and
  ## some matrices which need to be indexed accordingly
  if (!is.null(nrow(x))) x[, -wh] else x[-wh] 
  ## some of `bp` will not be present depending on how you called
  ## `boxplot`, so if that is the case, you need to leave them alone
  ## to keep the original structure so `bxp` can deal with it
  } else x)

## call `bxp` on the subset of `bp`
bxp(bp)

或者您可以使用任何您喜欢的值:

wh <- which(bp$n <= 1)

bp[] <- lapply(bp, function(x) if (length(x)) {
  if (!is.null(nrow(x))) x[, -wh] else x[-wh] 
} else x)

bxp(bp)