(tidyverse 方法)计算多列的 rowsum,其中要包含的列信息来自不同的数据框

des*_*hen 5 r tidyverse

假设有以下数据:

dat <- data.frame(x1 = c(1, 2, 3, 4, 5),
                  x2 = c(2, 3, 4, 5, 6),
                  x3 = c(3, 4, 5, 6, 7),
                  x4 = c(7, 2, 3, 4, 5),
                  x5 = c(7, 2, 1, 4, 5))
Run Code Online (Sandbox Code Playgroud)

进一步假设以下查找表:

lookup_positions <- data.frame(v1 = c(1,3,5),
                               v2 = c(1,2,5),
                               v3 = c(1,3,4),
                               v4 = c(2,3,5))
Run Code Online (Sandbox Code Playgroud)

现在,我想要做的是:对于 中的每一行,dat我想遍历 中指定的所有组合lookup_positions并计算 中指定的dat位置的行总和lookup_positions

所以对于所有行,dat我想计算 的行总和dat[,c(1,3,5)],然后我想计算等等的行总和dat[, c(1,2,5)]。所以我基本上计算了 4 行总和。

我知道如何使用一个循环做到这一点的基础R,我现在也怎么做,在tidyverse方法的一个行总和,但不知道如何做到这一点的中提到的所有版本中lookup_positions没有循环与tidyverse。

所以预期的结果是:

  x1 x2 x3 x4 x5 rowsum1 rowsum2 rowsum3 rowsum4
1  1  2  3  7  7      11      10      11      12
2  2  3  4  2  2       8       7       8       9
3  3  4  5  3  1       9       8      11      10
4  4  5  6  4  4      14      13      14      15
5  5  6  7  5  5      17      16      17      18
Run Code Online (Sandbox Code Playgroud)

这是我在 tidyverse 中的一个 lookup_positions 中得到的。但我被困在如何将其概括为所有查找位置。

dat %>%
  mutate(rowsum1 = apply(across(everything()), 1, function(x) sum(x[as.numeric(lookup_positions[1,])])))
Run Code Online (Sandbox Code Playgroud)

我知道对于我的 4 个查找位置,我可以简单地复制粘贴并完成它,但我的现实生活数据有几百个查找位置组合。

tmf*_*mnk 4

一种dplyr选择purrr可能是:

map2(.x = asplit(lookup_positions, 2),
     .y = 1:ncol(lookup_positions),
     ~ dat %>%
      mutate(!!paste0("rowsums", .y) := rowSums(select(., .x)))) %>%
 reduce(full_join)

  x1 x2 x3 x4 x5 rowsums1 rowsums2 rowsums3 rowsums4
1  1  2  3  7  7       11       10       11       12
2  2  3  4  2  2        8        7        8        9
3  3  4  5  3  1        9        8       11       10
4  4  5  6  4  4       14       13       14       15
5  5  6  7  5  5       17       16       17       18
Run Code Online (Sandbox Code Playgroud)