等价于R中的numpy.roll()? [英] Equivalent to numpy.roll() in R?

查看:73
本文介绍了等价于R中的numpy.roll()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

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

我想做些类似的事情:

b <- roll(a,2) # 4,5,1,2,3

R中是否有类似的功能?我一直在四处搜寻,但"R Roll"主要为我提供有关西班牙语发音的页面.

Is there a function like that in R? I've been googling around, but "R Roll" mostly gives me pages about Spanish pronunciation.

推荐答案

如何使用headtail ...

roll <- function( x , n ){
  if( n == 0 )
    return( x )
  c( tail(x,n) , head(x,-n) )
}

roll(1:5,2)
#[1] 4 5 1 2 3

#  For the situation where you supply 0 [ this would be kinda silly! :) ]
roll(1:5,0)
#[1] 1 2 3 4 5

关于使用headtail的一件很酷的事情...例如,您会得到一个负n的反向滚动,例如

One cool thing about using head and tail... you get a reverse roll with negative n, e.g.

roll(1:5,-2)
[1] 3 4 5 1 2

这篇关于等价于R中的numpy.roll()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆