Applying a function to every combination of elements in a vector

后端 未结 2 621
花落未央
花落未央 2021-01-05 14:12

I would like to apply a certain (custom) function to all combinations of an array. I think its best to explain with an example:

Matrix 1 :

A B C
1          


        
2条回答
  •  余生分开走
    2021-01-05 14:13

    This can be done simply if you install gtools and use the permutations function.

    require(gtools)
    M1 <- list(A=1, B=2, C=3)
    M2 <- list(A=4, B=5, C=6)
    
    perms <- t(permutations(3, 2, 1:3))
    
    comboList <- list()
    for (i in 1:ncol(perms)) {
        nameString <- paste0(names(M2)[perms[1,i]], names(M1)[perms[2,i]])
        comboList[[i]] <- mapply("/", M2[[perms[,i][1]]], M1[[perms[,i][2]]])
    }
    

    The mapply function is a pretty magical built in R function. It's worth while getting the know the entire family of *apply functions.

    The output is in comboList, which is as follows:

    > comboList
    $AB
    [1] 2
    
    $AC
    [1] 1.333333
    
    $BA
    [1] 5
    
    $BC
    [1] 1.666667
    
    $CA
    [1] 6
    
    $CB
    [1] 3
    

提交回复
热议问题