Applying a function to every combination of elements in a vector

后端 未结 2 606
花落未央
花落未央 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
    
    0 讨论(0)
  • 2021-01-05 14:34

    The result is not exactly in the format you asked for, but you can use outer to create a matrix of results from your two input vectors :

    x <- c(A=1,B=2,C=3)
    y <- c(A=4,B=5,C=6)
    outer(x,y, FUN="/")
    

    Will give :

         A   B         C
    A 0.25 0.2 0.1666667
    B 0.50 0.4 0.3333333
    C 0.75 0.6 0.5000000
    

    If you really want a vector as result, you can use :

    m <- outer(x,y, FUN="/")
    v <- as.vector(m)
    names(v) <- as.vector(outer(names(x),names(y),FUN="paste0"))
    

    And then get :

           AA        BA        CA        AB        BB        CB        AC 
    0.2500000 0.5000000 0.7500000 0.2000000 0.4000000 0.6000000 0.1666667 
           BC        CC 
    0.3333333 0.5000000 
    
    0 讨论(0)
提交回复
热议问题