Non-redundant version of expand.grid

后端 未结 7 1336
北海茫月
北海茫月 2020-12-01 01:56

The R function expand.grid returns all possible combination between the elements of supplied parameters. e.g.

> expand.grid(c(\"         


        
7条回答
  •  青春惊慌失措
    2020-12-01 02:25

    In base R, you can use this:

    expand.grid.unique <- function(x, y, include.equals=FALSE)
    {
        x <- unique(x)
    
        y <- unique(y)
    
        g <- function(i)
        {
            z <- setdiff(y, x[seq_len(i-include.equals)])
    
            if(length(z)) cbind(x[i], z, deparse.level=0)
        }
    
        do.call(rbind, lapply(seq_along(x), g))
    }
    

    Results:

    > x <- c("aa", "ab", "cc")
    > y <- c("aa", "ab", "cc")
    
    > expand.grid.unique(x, y)
         [,1] [,2]
    [1,] "aa" "ab"
    [2,] "aa" "cc"
    [3,] "ab" "cc"
    
    > expand.grid.unique(x, y, include.equals=TRUE)
         [,1] [,2]
    [1,] "aa" "aa"
    [2,] "aa" "ab"
    [3,] "aa" "cc"
    [4,] "ab" "ab"
    [5,] "ab" "cc"
    [6,] "cc" "cc"
    

提交回复
热议问题