Possible combinations of a matrix in R [closed]

纵饮孤独 提交于 2019-12-13 08:27:39

问题


I have a data frame as

df <- data.frame(x = c(1,2,3,4,5), y = c(11,12,13,14,15))

What I am trying to get is this

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

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.

Any ideas?


回答1:


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


来源:https://stackoverflow.com/questions/40229012/possible-combinations-of-a-matrix-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!