R:总是从vector中抓取n个元素,如果vector长度< n,则再次循环vector

u59ebvdq  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(93)

假设我有一组不同长度的向量。
我想总是从它们中抓取前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"
等等
有没有一种简单的方法可以做到这一点,而不需要遍历循环和异常?谢谢你,谢谢

zsohkypk

zsohkypk1#

可以使用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

7vux5j2d

7vux5j2d2#

我认为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"

相关问题