Non-redundant version of expand.grid

后端 未结 7 1334
北海茫月
北海茫月 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:43

    You can use a "greater than" operation to filter redundant combinations. This works with both numeric and character vectors.

    > grid <- expand.grid(c("aa", "ab", "cc"), c("aa", "ab", "cc"), stringsAsFactors = F)
    > grid[grid$Var1 >= grid$Var2, ]
      Var1 Var2
    1   aa   aa
    2   ab   aa
    3   cc   aa
    5   ab   ab
    6   cc   ab
    9   cc   cc
    

    This shouldn't slow down your code too much. If you're expanding vectors containing larger elements (e.g. two lists of dataframes), I recommend using numeric indices that refer to the original vectors.

提交回复
热议问题