循环通过向量 [英] Cycling through a vector
本文介绍了循环通过向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以在 R 中做到这一点:
I was wondering if it is possible in R to do it:
- 我有一个
list <- c(x1, x2, x3, x4, xn...)
- 使用 for 循环,将
x1
放在列表的底部,给出c(x2, x3, x4, xn.. x1)
. - 下一个循环将是
c(x3, x4, x5... x1, x2)
- I have a
list <- c(x1, x2, x3, x4, xn...)
- With a for loop, put
x1
at the bottom of the list givingc(x2, x3, x4, xn.. x1)
. - Next loop would be
c(x3, x4, x5... x1, x2)
这在 R 中可行吗?
推荐答案
我不知道你想做什么,但在下面的例子中,你可以看到"(print
) 循环在每次运行中的作用:
I don't know what you're trying to do, but in the following example, you can "see" (print
) what the loop does in each run:
#a vector (and not list)
vec <- c(5:10)
#the loop
for(i in seq_along(vec)) { print(c(vec[-(0:i)], vec[0:i])) }
#[1] 6 7 8 9 10 5
#[1] 7 8 9 10 5 6
#[1] 8 9 10 5 6 7
#[1] 9 10 5 6 7 8
#[1] 10 5 6 7 8 9
#[1] 5 6 7 8 9 10
如果您想存储输出而不仅仅是查看它,请考虑:
If you want to store the output and not just to see it, then consider this:
> result <- vector("list", length(vec))
> for(i in seq_along(vec)) {
result[[i]] <- c(vec[-(0:i)], vec[0:i])
}
>
> do.call(rbind, result)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 6 7 8 9 10 5
[2,] 7 8 9 10 5 6
[3,] 8 9 10 5 6 7
[4,] 9 10 5 6 7 8
[5,] 10 5 6 7 8 9
[6,] 5 6 7 8 9 10
为了避免列表中的预分配和for
循环和最后的rbind
ing,sapply
是不错的选择
In order to avoid pre-allocation in a list and the for
loop and rbind
ing at the end, sapply
is good option
sapply(1:length(vec), function(i) c(vec[-(0:i)], vec[0:i]))
这篇关于循环通过向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文