R 所有可能的组合 [英] R all possible combinations

查看:32
本文介绍了R 所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有空闲的数据框:

> my.df
          x         y
1 0.4597406 0.8439140
2 0.4579697 0.7461805
3 0.5593259 0.6646701
4 0.3607346 0.7792931
5 0.8377520 1.0445919
6 0.5597406 1.0445919

我想创建所有可能的组合

I want to create all possible combinations

> my.df
          x         y
1 0.4597406 0.8439140
2 0.4597406 0.7461805
3 0.4597406 0.6646701
4 0.4597406 0.7792931
5 0.4597406 1.0445919
6 0.4597406 1.0445919
7 0.4579697 0.8439140
8 0.4579697 0.7461805
9 0.4579697 0.6646701
... 
(Not all the combinations are showing here - This is to show the format that I would like to get the resulting data frame)

使用以下函数并没有真正给出确切的组合.

Using following functions didn't really give the exact combinations.

expand.grid(my.df)

生成所有可能组合的最佳方法是什么.

Whats the best way to generate all possible combinations.

推荐答案

expand.grid() 会给你所有可能的组合,但不是唯一的组合.如果你需要后者,你可以使用这样的函数

expand.grid() will give you all the possible combinations but not the unique combinations. If you need the latter you can use a function like this

unique_comb <- function(data){
   x.cur <- unique(data$x)
   y.cur <- unique(data$y)
   n.x <- length(x.cur)
   n.y <- length(y.cur)
   matrix.com <- matrix(0,ncol=2,nrow=n.x*n.y)
   ind <- 1
   for(i in 1:n.x){
       for(j in 1:n.y){
          matrix.com[ind,] <- c(x.cur[i],y.cur[j])
         ind <- ind+1
       }
   }
   return(matrix.com)
}

或者作为 JTT 点,这可以在一行中完成

Or as JTT points that this can be done in one line with

expand.grid(unique(data$x),unique(data$y)) 

这篇关于R 所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆