以百分比计算组间差异

calculate the difference between groups as a percentage

我有一个日期框:

data <- structure(list(col1 = c(10L, 8L, 5L, 4L, 6L, 3L), col2 = c(11L, 
9L, 6L, 3L, 4L, 6L), col3 = c(12L, 10L, 7L, 5L, 7L, 7L), group = c("a", 
"a", "b", "b", "c", "c")), class = "data.frame", row.names = c(NA, 
-6L))

我想找出所有组(a -b;a-c; b-c)之间的差异,并计算数字中有多少百分比来自数字(第一个数字取为100%)

我想得到的:

这是使用 combn -

的基础 R 方法
do.call(rbind, combn(unique(data$group), 2, function(x) {
  dt1 <- subset(data, group == x[1])
  dt2 <- subset(data, group == x[2])
  val1 <- abs(dt1[-4] - dt2[-4])
  val2 <- val1/dt1[-4]
  val2[] <- sprintf('%s (%s %%)', round(as.matrix(val1), 2),
                                  round(as.matrix(val2) * 100, 2))
  data.frame(val2, group = paste0(x, collapse = '-'))
}, simplify = FALSE))

#         col1        col2        col3 group
#1    5 (50 %) 5 (45.45 %) 5 (41.67 %)   a-b
#2    4 (50 %) 6 (66.67 %)    5 (50 %)   a-b
#3    4 (40 %) 7 (63.64 %) 5 (41.67 %)   a-c
#4  5 (62.5 %) 3 (33.33 %)    3 (30 %)   a-c
#31   1 (20 %) 2 (33.33 %)     0 (0 %)   b-c
#41   1 (25 %)   3 (100 %)    2 (40 %)   b-c