本文介绍了矢量的圆位移距离 n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有
a <- c(1, 2, 3)
并且我希望 b 通过向左"方向移动距离 1 来从 a 导出
and I want b to be derived from a by shifting it in direction "left" by distance 1
b
# [1] 2 3 1
推导我的意思是你:
- 将a"传递给一个吐出b"的函数
- 您使用了某种索引短文来做到这一点. 例如,
b <- c(2, 3, 1)
不是我要寻找的解决方案
- Pass "a" into a function that spits out "b"
- You use some sort of indexing short had which does that.
b <- c(2, 3, 1)
, for example, is not a solution I'm looking for
有什么优雅/有效的方法可以做到这一点?
What would be elegant/efficient ways to do that?
推荐答案
你可以利用 head
和 tail
来创建这样的函数:
You can make use of head
and tail
to create a function like this:
shifter <- function(x, n = 1) {
if (n == 0) x else c(tail(x, -n), head(x, n))
}
用法:
a <- 1:4
shifter(a)
# [1] 2 3 4 1
shifter(a, 2)
# [1] 3 4 1 2
(或者,library(SOfun); shifter(a)
你可以从 ).
(Or, library(SOfun); shifter(a)
where you can get SOfun
from here).
这篇关于矢量的圆位移距离 n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!