我正在尝试创建重叠间隔的数据。 我的数据集是:
A B
2 20
3 40
5 60
6 90
我希望得到:
A1 A2 B1 B2
2 3 20 40
3 5 40 60
5 6 60 90
答案 0 :(得分:3)
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
答案 1 :(得分:2)
如果您将数据放入矩阵(或将其转换为矩阵),那么您可以使用embed
函数,可能需要进行一些重新排列:
> 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
答案 2 :(得分:0)
非常手动:
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