Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract every nth element of a vector

Tags:

r

vector

People also ask

How do you extract every nth element of a vector in R?

The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration.

How do you take every nth row in R?

Use stripe(n, from = m) to get every nth row/column starting at row/column m. Use dplyr functions like starts_with , contains and matches to specify columns (but not rows).

How do I extract elements from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.

How do you find the nth value of a list?

To get every nth element in a list, a solution is to do mylist[::n].


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

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 ) ]

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

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