repeat the nth element every other n in a sequence

时间:2017-04-10 03:08:55

标签: r vector insert

the original vector x:

x = 1:20

and what i look for is a vector y that repeats the n-th element in x every other n, for instance, when n=4:

n = 4
y = c(1,2,3,4,4,5,6,7,8,8,9,10,11,12,12,13,14,15,16,16,17,18,19,20,20)

i'm actually doing it for matrices and i think it relates to the use of apply here when margin=2 but couldn't figure it out right off the bat, could anyone kindly show me a quick solution?

2 个答案:

答案 0 :(得分:4)

We can also use

v1 <- rep(1, length(x))
v1[c(FALSE, FALSE, FALSE, TRUE)] <- 2
rep(x, v1)
#[1]  1  2  3  4  4  5  6  7  8  8  9 10 11 12 12 13 14 15 16 16 17 18 19 20 20

Or as @MichaelChirico commented, the 2nd line of code can be made more general with

v1[seq_along(v1) %% n == 0L] = 2

Or in a one-liner with ifelse (from @JonathanCarroll's comments)

rep(x, ifelse(seq_along(x) %% n, 1, 2))

答案 1 :(得分:2)

Indeed matrices are the way to go

duplast = function(M) rbind(M, M[nrow(M), ])
c(duplast(matrix(x, nrow = 4L)))
#  [1]  1  2  3  4  4  5  6  7  8  8  9 10 11 12 12 13 14 15 16 16 17 18 19 20
# [25] 20

If you wanted to use apply:

c(apply(matrix(x, nrow = 4L), 2L, function(C) c(C, C[length(C)])))