如何在R中存在公式的情况下框绘子群

如何在R中存在公式的情况下框绘子群,r,boxplot,R,Boxplot,对我的情况既不适用也不适用 假设: 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) set.seed(42) x您可以使用粘贴创建一个新列(“xy”),使用具有多个元素的“xy”组的ave创建逻辑索引,然后执行箱线图 df1$xy <- factor(pas

对我的情况既不适用也不适用

假设:

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)
set.seed(42)

x您可以使用粘贴创建一个新列(“xy”),使用具有多个元素的“xy”组的ave创建逻辑索引,然后执行箱线图

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,]))

您可以查看任何
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)
set.seed(42)

df这比我冗长的解决方案要好得多,但我也希望摆脱
C.W
,因为它只有一个成员(我希望组中有多个成员)。您的解决方案适用于
>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)