【问题标题】:Sequence of two numbers with decreasing occurrence of one of them两个数字的序列,其中一个数字的出现次数减少
【发布时间】:2017-08-09 01:39:18
【问题描述】:

我想从两个数字创建一个序列,使得其中一个数字的出现减少(从n_1 到 1),而另一个数字的出现固定在n_2

我一直在寻找并尝试使用 seq 和 rep 来做到这一点,但我似乎无法弄清楚。

这是c(0,1)n_1=5n_2=3 的示例:

0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1

这里是c(0,1)n_1=2n_2=1

0,0,1,0,1

【问题讨论】:

    标签: r sequence seq rep


    【解决方案1】:

    也许是这样的?

    rep(rep(c(0, 1), n_1), times = rbind(n_1:1, n_2))
    ##  [1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
    

    这是一个函数(没有任何完整性检查):

    myfun <- function(vec, n1, n2) rep(rep(vec, n1), times = rbind(n1:1, n2))
    
    myfun(c(0, 1), 2, 1)
    ## [1] 0 0 1 0 1
    

    inverse.rle

    另一种选择是使用inverse.rle:

    y <- list(lengths = rbind(n_1:1, n_2),
              values = rep(c(0, 1), n_1))
    inverse.rle(y)
    ##  [1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
    

    【讨论】:

    • times = rbind(n_1:1, n_2) 没有c() 就足够了
    【解决方案2】:

    使用类似概念的替代方法(尽管速度较慢):

    unlist(mapply(rep,c(0,1),times=rbind(n_1:1,n_2)))
    ###[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
    

    【讨论】:

      【解决方案3】:

      这是使用矩阵的上三角形的另一种方法:

      f_rep <- function(num1, n_1, num2, n_2){
          m <- matrix(rep(c(num1, num2), times=c(n_1+1, n_2)), n_1+n_2+1, n_1+n_2+1, byrow = T)
          t(m)[lower.tri(m,diag=FALSE)][1:sum((n_1:1)+n_2)]
      }
      
      f_rep(0, 5, 1, 3)
      #[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
      
      f_rep(2, 4, 3, 3)
      #[1] 2 2 2 2 3 3 3 2 2 2 3 3 3 2 2 3 3 3 2 3 3 3
      

      【讨论】:

        【解决方案4】:
        myf = function(x, n){
            rep(rep(x,n[1]), unlist(lapply(0:(n[1]-1), function(i) n - c(i,0))))
        }
        myf(c(0,1), c(5,3))
        #[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
        

        【讨论】:

          猜你喜欢
          • 2017-07-26
          • 1970-01-01
          • 1970-01-01
          • 2023-01-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-06
          • 1970-01-01
          相关资源
          最近更新 更多