【问题标题】:Shift a sequence by certain interval in R [duplicate]在R中将序列移动一定间隔[重复]
【发布时间】:2019-09-11 18:07:05
【问题描述】:

R 中“将序列移动一定间隔”的最简单方法是什么(我不确定这是否是正确的术语)。例如,假设我们有一个函数 shift_seq(),它的工作原理如下:

x <- 1:7
shift_seq(x, 1) 
> 2, 3, 4, 5, 6, 7, 1
shift_seq(x, 2)
>  3, 4, 5, 6, 7, 1, 2

上面虚构的seq_shift()这样的函数是否存在?

更新:

显然,这个问题已经使用稍微不同的术语提出过。感谢@akrun 参考这些问题。尽管如此,用户 tmfmnk 提供了一种新的非常简洁的转换序列的方法(请参阅下面接受的答案)。在预览问题的答案中,引用了两个包含类似功能的包:permute::shuffleSeries()binhf::shift()

【问题讨论】:

    标签: r


    【解决方案1】:

    一种方法可能是:

    n <- 3
    c(x[-c(1:n)], x[1:n])
    
    [1] 4 5 6 7 1 2 3
    

    以函数的形式:

    shift_seq <- function(x, n) {
     c(x[-c(1:n)], x[1:n])
    }
    

    【讨论】:

      【解决方案2】:

      一种方式:

      foo = function(x, n){
        c(x[(n+1):(length(x))],x[1:n])
      }
      
      foo(7:1, 3)
      4 3 2 1 7 6 5
      

      【讨论】:

        【解决方案3】:

        这是一种使用headtail 的方法-

        shift_seq <- function(v, s) {
          c(tail(v, -s), head(v, s))
        }
        
        x <- 1:7
        
        shift_seq(x, 1)
        [1] 2 3 4 5 6 7 1
        
        shift_seq(x, 2)
        [1] 3 4 5 6 7 1 2
        

        【讨论】:

          【解决方案4】:
          x = 1:7
          
          shift_seq = function(x, n){
              ind = (seq_along(x) + n) %% (length(x))
              ind = replace(ind, ind == 0, length(x))
              x[ind]
          }
          
          shift_seq(x, 2)
          #> [1] 3 4 5 6 7 1 2
          shift_seq(x, -2)
          #> [1] 6 7 1 2 3 4 5
          

          reprex package (v0.3.0) 于 2019 年 9 月 11 日创建

          【讨论】:

            猜你喜欢
            • 2016-07-23
            • 1970-01-01
            • 2017-12-04
            • 2015-10-31
            • 2021-12-26
            • 2012-05-15
            • 1970-01-01
            • 1970-01-01
            • 2021-07-28
            相关资源
            最近更新 更多