(tidyverse方法)计算跨多个列的行和,其中要包含的列的信息来自不同的数据帧
假设以下数据:(tidyverse方法)计算跨多个列的行和,其中要包含的列的信息来自不同的数据帧,r,tidyverse,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)) 这是我在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))
这是我在tidyverse中的一个查找位置得到的信息。但是我被困在如何将其推广到所有查找位置
dat %>%
mutate(rowsum1 = apply(across(everything()), 1, function(x) sum(x[as.numeric(lookup_positions[1,])])))
我知道对于我的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
下面是您可能感兴趣的另一个
tidyverse
解决方案
library(dplyr)
library(purrr)
library(stringr)
dat %>%
mutate(map_dfc(
lookup_positions %>% rename_with(~str_replace(., "v", "rowsum")),
~rowSums(.y[, .x]),
across(everything())
))
输出
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
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
对于记录(我不知道tidyverse:-),使用data.table
和base R
library(data.table)
setDT(dat)
rowsumX <- gsub("v", "rowsum", names(lookup_positions))
dat[, by=seq_len(nrow(dat)),
(rowsumX) := lapply(lookup_positions, function(x) sum(unlist(.SD)[x]))
]
从
tidyverse
包中检查?行和()
。tidyverse中没有行和函数。此外,问题不在于如何计算行和,我的问题是将我的方法推广到多个查找位置。有趣。我不能说我完全理解这里发生的一切,但我一定会努力的。谢谢
library(data.table)
setDT(dat)
rowsumX <- gsub("v", "rowsum", names(lookup_positions))
dat[, by=seq_len(nrow(dat)),
(rowsumX) := lapply(lookup_positions, function(x) sum(unlist(.SD)[x]))
]
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