向量的圆位移(相当于numpy.roll) [英] Circular shift of vector (equivalent to numpy.roll)
本文介绍了向量的圆位移(相当于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.
推荐答案
如何使用 head
和 tail
...
How about using head
and tail
...
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
使用 head
和 tail
的一件很酷的事情......你会得到一个带有负 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
这篇关于向量的圆位移(相当于numpy.roll)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文