ronaldkelley
ronaldkelley

Reputation: 131

How to generate an output satisfied with specific conditions from expand.grid in R

I am running expand.grid function. For a simple example,

a <- c(1,2,3,"X","Y","M") 
b is identical as b.

if I take expand.grid(a,b), it returns all pairs including diagonal elements -- (1,1),(2,2),....(y,y), and also, elements which the first of pairs is larger than the second one --(2,1),(3,2)(x,1),...etc. (but, actually, not numerical comparison here as there are some characters like x,y) I want to exclude such pairs in output. How can I simply generate the output without them by using expand.grid function, Or, any other functions to do it?

Upvotes: 1

Views: 305

Answers (3)

Saar
Saar

Reputation: 66

A slight modification to Vincent Zoonekynd's will take care of non-numerical factors:

a <- c(1,2,3,"X","Y","M")
eg <- expand.grid(a,a)
eg2 <- eg[as.character(eg$Var1) < as.character(eg$Var2), ]

Basically, what you need is to use string comparison instead of "plain" comparison that doesn't work on factor variables.

Upvotes: 1

IRTFM
IRTFM

Reputation: 263481

 eg <- expand.grid(a=1:4, b=1:4)

> eg[eg$a < eg$b, ]
   a b
5  1 2
9  1 3
10 2 3
13 1 4
14 2 4
15 3 4

Here' another potentially useful function combn which retruns a matrix that needs to be transposed to get what you ask for:

> data.frame(t(combn(x=1:4, m=2)))
  X1 X2
1  1  2
2  1  3
3  1  4
4  2  3
5  2  4
6  3  4

Upvotes: 2

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32401

You can just take the subset you are interested in:

a <- b <- 1:5
subset( expand.grid(a,b), Var1 < Var2 )

Upvotes: 0

Related Questions