用 R 求和成对行? [英] Sum pairwise rows with R?
本文介绍了用 R 求和成对行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的输入是
df1 <- data.frame(Row=c("row1", "row2", "row3", "row4", "row5"),
A=c(1,2,3,5.5,5),
B=c(2,2,2,2,0.5),
C= c(1.5,0,0,2.1,3))
看起来像这样:
# Row1 1 2 1.5
# Row2 2 2 0
# Row3 3 2 0
# Row4 5.5 2 2.1
# Row5 5 0.5 3
我想使用以下等式获得所有这些行对的总和.让我们说 Row1 和 Row2 对:我想将每一列的条目相乘并将它们相加为一个最终答案,例如-
I want to get the sum of all these pairs of rows, with the following equation. Let's said for Row1 and Row2 pairs: I want to multiply each column's entry and sum them into one final answer, for example-
- Row1-Row2 答案是
(1*2) + (2*2)+ (1.5 *0)
=6
- Row1-Row3 答案是
(1*3) + (2*2) + (1.5*0)
=7
- Row1-Row2 answer is
(1*2) + (2*2)+ (1.5 *0)
=6
- Row1-Row3 answer is
(1*3) + (2*2) + (1.5*0)
=7
我想对每一对行进行所有分析,并得到这样的结果数据框:
I want to do all analysis for each pairs of row and get a result data frame like this:
row1 row2 6
row1 row3 7
row1 row4 12.65
row1 row5 10.5
row2 row3 10
row2 row4 15
row2 row5 11
row3 row4 20.5
row3 row5 16
row4 row5 34.8
我怎样才能用 R 做到这一点?非常感谢评论.
How can I do this with R? Thanks a lot for comments.
推荐答案
- 使用
combn
创建您需要的所有组合.t
用于按照您期望的格式对矩阵进行转置. - 使用
apply
迭代步骤 1 中创建的索引.请注意,我们使用负索引,因此我们不会尝试对 Row 列求和. - 将两个结果绑定在一起.
- Create all the combinations you need with
combn
.t
is used to transpose the matrix as you expect it to be formatted. - Use
apply
to iterate over the indices created in step 1. Note that we use negative indexing so we don't try to sum the Row column. - Bind the two results together.
`
ind <- t(combn(nrow(df1),2))
out <- apply(ind, 1, function(x) sum(df1[x[1], -1] * df1[x[2], -1]))
cbind(ind, out)
out
[1,] 1 2 6.00
[2,] 1 3 7.00
[3,] 1 4 12.65
.....
这篇关于用 R 求和成对行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文