Reputation: 293
I am trying to create data with overlapping intervals. My data set is:
A B
2 20
3 40
5 60
6 90
and I want to get:
A1 A2 B1 B2
2 3 20 40
3 5 40 60
5 6 60 90
Upvotes: 2
Views: 284
Reputation: 49660
If you put your data into a matrix (or convert it to a matrix) then you can use the embed
function, possibly with a little bit of rearranging:
> mydat <- cbind( A=c(2,3,5,6), B=c(20,40,60,90) )
> embed(mydat, 2)
[,1] [,2] [,3] [,4]
[1,] 3 40 2 20
[2,] 5 60 3 40
[3,] 6 90 5 60
> embed(mydat, 2)[,c(3,1,4,2)]
[,1] [,2] [,3] [,4]
[1,] 2 3 20 40
[2,] 3 5 40 60
[3,] 5 6 60 90
Upvotes: 2
Reputation: 12829
do.call(cbind, lapply(x, embed, dimension=2))
[,1] [,2] [,3] [,4]
[1,] 3 2 40 20
[2,] 5 3 60 40
[3,] 6 5 90 60
Upvotes: 3
Reputation: 7794
Very manually:
df1 <- data.frame(A=c(2,3,5,6),B=c(20,40,60,90))
df2 <- data.frame(A1=t(combn(df1$A,2))[,1],A2=t(combn(df1$A,2))[,2])
df2 <- df2[which(!duplicated(df2[,1])),]
df2$B1 <- df1[match(df2[,1],df1[,1]),2]
df2$B2 <- df1[match(df2[,2],df1[,1]),2]
> df2
A1 A2 B1 B2
1 2 3 20 40
4 3 5 40 60
6 5 6 60 90
Upvotes: 0