gpt4 book ai didi

每第 n 个元素重复序列 x 次

转载 作者:行者123 更新时间:2023-12-05 01:03:49 24 4
gpt4 key购买 nike

我有一个向量,例如:

v <- c(1, 2, 3, 4)

我想将每个第 n 个元素的序列重复 x 次,例如:

x=2
n= 2

[1] 1, 2, 1, 2, 3, 4, 3, 4

我知道

rep(v, times=n)
[1] 1, 2, 3, 4, 1, 2, 3, 4

rep(v, each=n)
[1] 1, 1, 2, 2, 3, 3, 4, 4

谢谢!

最佳答案

你可以分割向量然后重复:

fun <- function(v, m, n) {
unlist(by(v, ceiling(seq_along(v) / m), rep, n), use.names = FALSE)
}
v <- c(1, 2, 3, 4)

fun(v, 2, 2)
# [1] 1 2 1 2 3 4 3 4

fun(v, 3, 3)
# [1] 1 2 3 1 2 3 1 2 3 4 4 4

关于每第 n 个元素重复序列 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73392048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com