简体   繁体   English

查找不同列中不同行的总和

[英]Finding sums of different rows in different columns

I'm trying to find the sum of different rows in different columns.我试图找到不同列中不同行的总和。 For example, in the made-up data below I would like to know the sum of row 3-5 from exp1, 6-8 from exp2, and 2-4 from exp3, returning 12, 51, 69 for each column respectively.例如,在下面的虚构数据中,我想知道 exp1 的第 3-5 行、exp2 的 6-8 行和 exp3 的 2-4 行的总和,每列分别返回 12、51、69。

 > data
   exp1 exp2 exp3
1     1   11   21
2     2   12   22
3     3   13   23
4     4   14   24
5     5   15   25
6     6   16   26
7     7   17   27
8     8   18   28
9     9   19   29
10   10   20   30

I have the range of the row index that I want as two separate named numeric objects, lower being one value smaller than my intended row index because of what I'm doing next.我有我想要的行索引范围作为两个单独的命名数字对象,因为我接下来要做什么,所以比我预期的行索引小一个值。

> upper
exp1 exp2 exp3 
   5    8    4 
> lower
exp1 exp2 exp3 
   2    5    1 

What I've tried is to slice out row 1:upper and row 1:lower with a loop.我尝试的是用循环切出第1:upper和第1:lower

output <- list()
for (i in 1:length(data)) {
  temp <- data[i]
  output[[i]] <- slice(temp, 1:upper[i])
}

This creates two new dataframes, allowing me to find colSums of both of them, then subtracting 1:lower from 1:upper.这会创建两个新的数据框,让我可以找到它们的colSums ,然后从 1:upper 中减去 1:lower。 So I did manage to get a sum for each column, but even to someone new to R this seems to be a really convoluted way of doing things, so I'm wondering if there's a cleaner way to achieve the same outcome.所以我确实设法为每一列得到了一个总和,但即使对于 R 的新手来说,这似乎是一种非常复杂的做事方式,所以我想知道是否有更清洁的方法来实现相同的结果。

Any advice would be very appreciated, thank you!任何建议将不胜感激,谢谢!

You can use mapply :您可以使用mapply

mapply(function(x, y, z) sum(z[x:y]), lower + 1, upper, data)

#exp1 exp2 exp3 
#  12   51   69 

data数据

data <- structure(list(exp1 = 1:10, exp2 = 11:20, exp3 = 21:30), 
class = "data.frame", row.names = c(NA, -10L))
upper <- c('exp1' = 5, 'exp2' = 8, 'exp3' = 4)
lower <- c('exp1' = 2, 'exp2' = 5, 'exp3' = 1)

Using pmap使用pmap

library(purrr)
pmap_dbl(list(data, lower+1, upper), ~ sum(..1[..2:..3]))
# exp1 exp2 exp3 
#  12   51   69 

data数据

data <- structure(list(exp1 = 1:10, exp2 = 11:20, exp3 = 21:30), 
class = "data.frame", row.names = c(NA, -10L))
upper <- c('exp1' = 5, 'exp2' = 8, 'exp3' = 4)
lower <- c('exp1' = 2, 'exp2' = 5, 'exp3' = 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM