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

查看:93
本文介绍了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天全站免登陆