R中矩阵的可能组合 [英] Possible combinations of a matrix in R
本文介绍了R中矩阵的可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框
df <- data.frame(x = c(1,2,3,4,5), y = c(11,12,13,14,15))
我想得到的是这个
df
1 11
2 12
3 13
4 14
5 15
2 12
3 13
4 14
5 15
3 13
4 14
5 15
5 15
基本上是数据的所有可能组合帧。我试过了combin和expand.grid,但是它们给了我所有可能的组合,而不是一次所有的可能组合。我也尝试过循环播放,但是子集总是折腾。
It basically is all the possible combinations of the data frame. I tried combn and expand.grid but they give me all possible combinations, not all possible combinations taken two at a time. I also tried looping it but the subsetting always goes for a toss.
有什么想法吗?
推荐答案
我们可以使用 sapply
迭代按对对进行排序。然后将向量与索引绑定:
We can sequence by the pairs with an sapply
iteration. Then binding the vectors with the index:
df <- data.frame(x = c(1,2,3,4,5), y = c(11,12,13,14,15))
s <- seq(length(df$x))
d2 <- unlist(sapply(s, seq, to=max(s)))
cbind.data.frame(x=df$x[d2], y=df$y[d2])
# x y
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15
# 6 2 12
# 7 3 13
# 8 4 14
# 9 5 15
# 10 3 13
# 11 4 14
# 12 5 15
# 13 4 14
# 14 5 15
# 15 5 15
这篇关于R中矩阵的可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文