Suppose I have a vector c(1, 2, 3, 4)
with no duplicated values. I need a vector c(1 * 2, 1 * 3, 1 * 4, 2 * 3, 2 * 4, 3 * 4)
, so the multiplication is done in all possible combinations of this vector's values. Is there a way of doing that? Thanks in advance!
相关问题
- R - Quantstart: Testing Strategy on Multiple Equit
- Using predict with svyglm
- Reshape matrix by rows
- Extract P-Values from Dunnett Test into a Table by
- split data frame into two by column value [duplica
相关文章
- How to convert summary output to a data frame?
- How to plot smoother curves in R
- Paste all possible diagonals of an n*n matrix or d
- ess-rdired: I get this error “no ESS process is as
- How to use doMC under Windows or alternative paral
- dyLimit for limited time in Dygraphs
- Saving state of Shiny app to be restored later
- How to insert pictures into each individual bar in
We can use
combn
with anonymous function calldata
This is fun enough. I thought
combn(1:4, 2, "*")
would be the simplest solution but it actually does not work. We have to usecombn(1:4, 2, prod)
as Onyambu commented. The issue is: in an "N choose K" setting,FUN
must be able to take a vector of length-K as input."*"
is not the right one.We are going too far, but we will meet this sooner or later
Thanks Maurits Evers for elaboration on
outer
/lower.tri
/upper.tri
. Here is an adapted way to avoid generating those temporary matrices fromouter
and*****.tri
:The
tri_ind
function is wrapper of my this answer. It could be used as a fast and memory-efficient alternative forcombn(length(vec), 2)
or itsouter
-equivalence.Originally I linked an
finv
function but it is not good for benchmarking, as it is designed for extracting a few elements from a "dist" object (a collapsed lower triangular matrix). If all elements of the triangular matrix are referenced, its index computation actually imposes unnecessary overhead.tri_ind
is a better option.benchmark index generation
benchmark on OP's problem
For me, it is interesting to know that
combn
is not written in compiled code. It actually has an R-level for loop inside. The various alternatives is just trying to speed it up in "N choose 2" case without writing compiled code.Better choice??
Function
combinations
fromgtools
package uses recursive algorithm, which is problematic for big problem size. Functioncombn
fromcombinat
package does not use compiled code so it is no better thancombn
from R core. TheRcppAlgos
package by Joseph Wood has acomboGenearl
function which is the fastest one I see so far.Joseph Wood has various answers on combinations / permutations. For example: Faster version of combn.
Here is the "
outer
+ upper triangular part option"Another method is to index the elements of the upper/lower triangular part of a matrix directly and then calculate the pairwise product for those elements (adapted from this post)
Benchmark analysis
It's interesting to compare the different methods in a
microbenchmark
analysis for a largervector
(e.g.1:100
):