Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all possible two column subsets

Tags:

r

I am a relative newbie to R and I am now very close to being finished with a rather long script with many thanks to everyone who helped me thus far at various steps. I have another point I am stuck on. I have simplified the issue to this:

Dataset1
ax ay
1  3
2  4

Dataset2
bx by
5   7
6   8

A <- dataset1
B <- dataset2
a <- 2 #number of columns
b <- 1:2

(my datasets will vary in number of columns and so I need to be able to vary this factor)

I want this answer in any order (i.e. all possible combinations of two columns one from each of the two datasets) like this or equivalent.

[[1]]
1  5
2  6

[[2]]
1  7
2  8

[[3]]
3  5
4  6

[[4]]
3  7
4  8

But I am not getting it. I tried a bunch of things and the closest to what I want was with this:

i <- 1
for( i in 1:a )
 {
   e <- lapply(B, function(x) as.data.frame(cbind(A, x)))
   print(e)
   i <- i+1
  }

Close, yes. I can take the answer and do some fiddling and subsetting but its not right and there must be an easy way to do this. I have not seen anything like this in my on line searches. Any help much appreciated.

like image 579
Natalie Bjorklund Avatar asked Feb 17 '23 08:02

Natalie Bjorklund


1 Answers

Does something like this work for you?

Dataset1 <- data.frame(ax=1:2,ay=3:4)
Dataset2 <- data.frame(bx=5:6,by=7:8)

apply(
    expand.grid(seq_along(Dataset1),seq_along(Dataset2)),
    1,
    function(x) cbind(Dataset1[x[1]],Dataset2[x[2]])
     )

Result:

[[1]]
  ax bx
1  1  5
2  2  6

[[2]]
  ay bx
1  3  5
2  4  6

[[3]]
  ax by
1  1  7
2  2  8

[[4]]
  ay by
1  3  7
2  4  8
like image 60
thelatemail Avatar answered Feb 28 '23 19:02

thelatemail