[英]Finding the index of the vector for the sum of pairwise in R
When I run this code当我运行此代码时
x <- c(2, 2, 10, 8)
combn(x, 2, sum)
I get我得到
> combn(x, 2, sum)
[1] 4 12 10 12 10 18
How do I get the index for x for any of the combn?如何获得任何组合的 x 的索引? For this question, the 4 is the sum of 2 + 2 which is x[1] + x[2].
对于这个问题,4 是 2 + 2 的总和,即 x[1] + x[2]。 I need the index [1] and [2] for x.
我需要 x 的索引 [1] 和 [2]。
This code will give you the first element of the combination in the first line, the second in the second, and in the last line you'll get the sum:此代码将在第一行中为您提供组合的第一个元素,在第二行中为您提供第二个元素,在最后一行中您将获得总和:
combn(x, 2, function(x) c(x, sum(x)))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 2 2 2 2 2 10
[2,] 2 10 8 10 8 8
[3,] 4 12 10 12 10 18
If you want the output as a data.frame
:如果您希望输出为
data.frame
:
t(combn(x, 2, function(x) c(x, sum(x))))-> l
dimnames(l)[[2]] <- c(paste0("X",1:2), "Sum")
as.data.frame(l)
X1 X2 Sum
1 2 2 4
2 2 10 12
3 2 8 10
4 2 10 12
5 2 8 10
6 10 8 18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.