总是从vector中抓取n个元素,如果vector length < n,则再次遍历vector

bt1cpqcv  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(127)

假设我有一组不同长度的向量。
我想总是从它们中提取前9个元素。
然而,如果向量长度<9,我想抓住所有的元素,并完成9再次遍历向量(一次又一次.必要时)从一开始。
举例来说:
v1=LETTERS[1:15]->我要抓取"A" "B" "C" "D" "E" "F" "G" "H" "I"
v2=LETTERS[1:5]->我要抓取"A" "B" "C" "D" "E" "A" "B" "C" "D"
v3=LETTERS[1:3]->我要抓取"A" "B" "C" "A" "B" "C" "A" "B" "C"
等等
有没有一种简单的方法可以做到这一点,而不需要遍历循环和异常?

yc0p9oo0

yc0p9oo01#

可以使用rep()函数:

> rep(LETTERS[1:15], length.out = 9)
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I"
> rep(LETTERS[1:5], length.out = 9)
[1] "A" "B" "C" "D" "E" "A" "B" "C" "D"
> rep(LETTERS[1:3], length.out = 9)
[1] "A" "B" "C" "A" "B" "C" "A" "B" "C"

阅读文档here

ergxz8rk

ergxz8rk2#

我认为rep approach by @Mark是最直接和有效的方式为您的问题。
如果你对编码实践感兴趣,你可以尝试像下面这样定义一个函数

f <- function(v, n) {
    v[(seq(n) - 1) %% length(v) + 1]
}

使得

> f(LETTERS[1:9], 9)
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I"

> f(LETTERS[1:5], 9)
[1] "A" "B" "C" "D" "E" "A" "B" "C" "D"

> f(LETTERS[1:3], 9)
[1] "A" "B" "C" "A" "B" "C" "A" "B" "C"

相关问题