I have a vector e.g:
v <- c(1, 2, 3, 4)
I want to repeat the sequence of every nth element x times e.g:
x=2
n= 2
[1] 1, 2, 1, 2, 3, 4, 3, 4
I know that
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
Thanks!
CodePudding user response:
You could split the vector and then repeat:
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
CodePudding user response:
Another split
option:
unlist(rep(split(v,(seq_along(v)-1) %/% n), each = x), use.names = FALSE)
#[1] 1 2 1 2 3 4 3 4
CodePudding user response:
We may create a grouping index with gl
and use tapply
f_rep <- function(v, x, n)
{
unname(unlist(tapply(v, as.integer(gl(length(v), x,
length(v))), rep, times = n)))
}
-testing
> x <- 2
> n <- 2
> f_rep(v, x, n)
[1] 1 2 1 2 3 4 3 4
> f_rep(v, 3, 3)
[1] 1 2 3 1 2 3 1 2 3 4 4 4
CodePudding user response:
With sequence
:
v <- 9:1
x <- 2L
n <- 3L
v[sequence(rep(n, x*(length(v) %/% n)), rep(seq(1, length(v), n), each = x))]
#> [1] 9 8 7 9 8 7 6 5 4 6 5 4 3 2 1 3 2 1
If it needs to handle vectors whose lengths are not multiples of n
:
v <- 1:5
x <- 3L
n <- 3L
v[
sequence(
c(
rep(n, x*(length(v) %/% n)),
rep(length(v) %% n, x)
),
c(
rep(seq(1, length(v), n), each = x),
length(v) - length(v) %% n 1L
)
)
]
#> [1] 1 2 3 1 2 3 1 2 3 4 5 4 5 4 5