使用应用系列或循环复制 dplyr 管道结构

Replicating dplyr pipe structure with apply family or loop

我有一个数据框 df,对于其中的每一列,我想计算在另一列中出现的频率。每行事件都有一个权重,所以理想情况下我想获得加权份额。

A <- c(0, 1, 0, 0, 1, 0, 1, 1, 1, 0)
B <- c(0, 1, 0, 1, 1, 0, 0, 0, 0, 0)
C <- c(0, 0, 0, 1, 1, 0, 0, 0, 0, 1)
D <- c(1, 0, 0, 1, 1, 0, 0, 0, 0, 0)
weight <- c(0.5, 1, 0.2, 0.3, 1.4, 1.5, 0.8, 1.2, 1, 0.9)
df <- data.frame(A, B, C, D, weight)

我试图用这种方式为每对列计算它:

#total weight of occurences in A
wgt_A <- df%>%
  filter(A == 1)%>%
  summarise(weight_A = sum(weight))%>%
  select(weight_A)

#weighted share of occurrences in A that also occur in B
wgt_A_B <- df%>%
  filter(A == 1, B == 1)%>%
  summarise(weight_A_B = sum(weight))%>%
  select(weight_A_B)

Result_1 <- wgt_A_B / wgt_A 

对于 4 列的所有组合,我希望最终得到总共 6 个结果。但是,为此我需要多次复制这个 dplyr 管道,而我的实际数据集有 20 多个这样的列。是否有更多的 efficient/quicker 方法来使用 apply/sapply 或某种循环来执行此操作,我还可以 select 我想对哪些列执行此操作?

我是 R 和 Whosebug 的新手所以如果我 doing/saying 有什么蠢事请告诉我(请原谅)

我们可以用combn来组合base R

out <- combn(df[1:4], 2, FUN = function(x)
    sum(df$weight[x[[1]] & x[[2]]])/ sum(df$weight[as.logical(x[[1]])]) )
names(out) <- combn(names(df)[1:4], 2, FUN = paste, collapse = "_")

-输出

> out
      A_B       A_C       A_D       B_C       B_D       C_D 
0.4444444 0.2592593 0.2592593 0.6296296 0.6296296 0.6538462