【问题标题】:R: forming all consecutive combinations from a vectorR:从一个向量形成所有连续的组合
【发布时间】:2016-01-04 15:52:06
【问题描述】:

假设我有一个这样的向量:

a<-c(1,2,3,4)

我如何从中获得所有连续的组合,例如:

1,2,3,4
2,3,4,1
3,4,1,2
4,1,2,3

但没有别的? 不幸的是,我的向量要大得多,所以手工操作会花费太多时间。 感谢您的帮助。

【问题讨论】:

    标签: r combinations combinatorics


    【解决方案1】:

    我们可以使用matrix

     matrix(a, ncol=4, nrow=5)[1:4,]
     #       [,1] [,2] [,3] [,4]
     #[1,]    1    2    3    4
     #[2,]    2    3    4    1
     #[3,]    3    4    1    2
     #[4,]    4    1    2    3
    

    我们可以将以上概括为

     n <- length(a)
     matrix(a, ncol=n, nrow=n+1)[seq(n),]
    

    【讨论】:

    • 不错。也许进一步概括
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多