如何为分组数据创建组内欧氏距离的箱线图?

How can I create a boxplot of within-group euclidian distances for grouped data?

示例数据:

set.seed(1234)
a <- matrix(rnorm(250),nrow=25,ncol=10)
fac <- as.factor(c(rep("A",8),rep("B",10),rep("C",7)))
a.dist <- dist(a, "euclidian")
boxplot(a.dist ~ fac)

当我尝试 运行 boxplot(a.dist ~ fac) 时,出现以下错误:

Error in model.frame.default(formula = a.dist ~ fac) : 
  variable lengths differ (found for 'fac')

我试图通过

解决这个问题
a.dist <- as.matrix(a.dist)
a.dist[upper.tri(a.dist)] <- NA

但后来 boxplot returns 给我一个有趣的情节。

我可以用

绘制特定组的组内欧氏距离
subset <- as.factor(fac) %in% ("A")
a.dist.A <- a.dist[subset]
boxplot(a.dist.A)

基本上我需要为每个因子级别执行此操作,然后将这些箱线图组合成一个箱线图。有没有简单的方法?

set.seed(1234)
a <- matrix(rnorm(250),nrow=25,ncol=10)
fac <- as.factor(c(rep("A",8),rep("B",10),rep("C",7)))

a_grp <- split.data.frame(a, fac)    ## split matrix by group
d_grp <- lapply(a_grp, dist)         ## apply `dist` by group
n_grp <- lengths(d_grp)              ## number of pairs by group
d <- unlist(d_grp)                   ## combine
g <- rep(factor(levels(fac), levels = levels(fac)), n_grp)  ## combine
boxplot(d ~ g)                       ## joint plot

按组应用 dist 是必要的,因为您不需要组间距离。