It works (maybe in order)
firstdf <- data.frame(x = c( 1, 2, 4, 5), y1 = c(43,51,57,49), y2 = c(55,53,47,44)) co <- combn(firstdf$x,2) seconddf <- data.frame(xi = c(co[1,], co[2,]), xj = c(co[2,], co[1,])) thirddf <- merge(merge(seconddf, firstdf, by.x = "xj", by.y = "x" ), firstdf, by.x = "xi", by.y = "x", suffixes = c("j", "i") )
for creating
> thirddf xi xj y1j y2j y1i y2i 1 1 2 51 53 43 55 2 1 5 49 44 43 55 3 1 4 57 47 43 55 4 2 4 57 47 51 53 5 2 1 43 55 51 53 6 2 5 49 44 51 53 7 4 5 49 44 57 47 8 4 1 43 55 57 47 9 4 2 51 53 57 47 10 5 1 43 55 49 44 11 5 2 51 53 49 44 12 5 4 57 47 49 44
where the first and fifth lines correspond to your example.
If you take firstdf as firstdf and insist on one line, you can include it in
merge(merge(data.frame(xi = c(combn(firstdf$x,2)[1,], combn(firstdf$x,2)[2,]), xj = c(combn(firstdf$x,2)[2,], combn(firstdf$x,2)[1,])), firstdf, by.x = "xj", by.y = "x" ), firstdf, by.x = "xi", by.y = "x", suffixes = c("j", "i") )
but i really don't see the point