Extract every nth element of a vector

RVector

R Problem Overview


I would like to create a vector in which each element is the i+6th element of another vector.

For example, in a vector of length 120 I want to create another vector of length 20 in which each element is value i, i+6, i+12, i+18... of the initial vector, i.e. I want to extract every 6th element of the original.

R Solutions


Solution 1 - R

a <- 1:120
b <- a[seq(1, length(a), 6)]

Solution 2 - R

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Solution 3 - R

I think you are asking two things which are not necessarily the same

> I want to extract every 6th element of > the original

You can do this by indexing a sequence:

foo <- 1:120
foo[1:20*6]

> I would like to create a vector in > which each element is the i+6th > element of another vector.

An easy way to do this is to supplement a logical factor with FALSEs until i+6:

foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1]   7  14  21  28  35  42  49  56  63  70  77  84  91  98 105 112 119

i <- 10
foo[1:(i+6)==(i+6)]
[1]  16  32  48  64  80  96 112

Solution 4 - R

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

Solution 5 - R

To select every n-th element with an offset/shift of f=0,...,n-1, use

vec[mod(1:length(vec), n)==f]

Of course, you can wrap this in a nice function:

nth_element <- function(vec, interval, offset=0){
    vec[mod(1:length(vec), interval)==mod(offset, interval)]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThallyHoView Question on Stackoverflow
Solution 1 - RnicoView Answer on Stackoverflow
Solution 2 - RGreg SnowView Answer on Stackoverflow
Solution 3 - RSacha EpskampView Answer on Stackoverflow
Solution 4 - RstevecView Answer on Stackoverflow
Solution 5 - Ruser11130854View Answer on Stackoverflow