简体   繁体   English

获取数据框中多个列的成对和

[英]get pairwise sums of multiple columns in dataframe

I have a dataframe that looks like this: 我有一个看起来像这样的数据框:

x<-data.frame(a=6, b=5:1, c=7, d=10:6)

> x
  a b c  d
1 6 5 7 10
2 6 4 7  9
3 6 3 7  8
4 6 2 7  7
5 6 1 7  6

I am trying to get the sums of columns a & b and c & d in another data frame that should look like: 我正在尝试获取另一个数据框中的列abcd的总和,如下所示:

> new
  ab cd
1 11 17
2 10 16
3  9 15
4  8 14
5  7 13

I've tried the rowSums() function but it returns the sum of ALL the columns per row, and I tried rowSums(x[c(1,2), c(3,4)]) but nothing works. 我试过rowSums()函数,但它返回每行所有列的总和,我试过了rowSums(x[c(1,2), c(3,4)])但没有任何效果。 Please help!! 请帮忙!!

You can use rowSums on a column subset. 您可以在列子集中使用rowSums

As a data frame: 作为数据框:

data.frame(ab = rowSums(x[c("a", "b")]), cd = rowSums(x[c("c", "d")]))
#   ab cd
# 1 11 17
# 2 10 16
# 3  9 15
# 4  8 14
# 5  7 13 

As a matrix: 作为矩阵:

cbind(ab = rowSums(x[1:2]), cd = rowSums(x[3:4]))

For a wider data frame, you can also use sapply over a list of column subsets. 对于更宽的数据框,您还可以在列子集列表中使用sapply

sapply(list(1:2, 3:4), function(y) rowSums(x[y]))

For all pairwise column combinations: 对于所有成对的列组合:

y <- combn(ncol(x), 2L, function(y) rowSums(x[y]))
colnames(y) <- combn(names(x), 2L, paste, collapse = "")
y
#      ab ac ad bc bd cd
# [1,] 11 13 16 12 15 17
# [2,] 10 13 15 11 13 16
# [3,]  9 13 14 10 11 15
# [4,]  8 13 13  9  9 14
# [5,]  7 13 12  8  7 13

Here's another option: 这是另一个选择:

> sapply(split.default(x, 0:(length(x)-1) %/% 2), rowSums)
      0  1
[1,] 11 17
[2,] 10 16
[3,]  9 15
[4,]  8 14
[5,]  7 13

The 0:(length(x)-1) %/% 2 step creates a sequence of groups of 2 that can be used with split . 0:(length(x)-1) %/% 2步骤创建了一组2组,可与split一起使用。 It will also handle odd numbers of columns (treating the final column as a group of its own). 它还将处理奇数列(将最后一列作为一组处理)。 Since there's a different default split "method" for data.frame s that splits by rows, you need to specify split.default to split the columns into groups. 由于data.frame的默认split “方法”是按行拆分的,因此您需要指定split.default将列拆分为组。

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

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