Select Every Other Element from a Vector

Select every other element from a vector

remove[c(TRUE, FALSE)]

will do the trick.


How it works?

If logical vectors are used for indexing in R, their values are recycled if the index vector is shorter than the vector containing the values.

Here, the vector remove contains ten values. If the index vector c(TRUE, FALSE) is used, the actual command is: remove[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)]

Hence, all values with odd index numbers are selected.

Extract every nth element of a vector

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

split a vector and fill every other element in order to have specific length

Here is one way to do it :

apply_fun <- function(vec, s) {
#Initialize the vector with NA
ans <- rep(NA, length(vec))
#Create groups to calculate mean
groups <- rep(1:s, ceiling(length(vec) / s),length.out = length(vec))
#Create indices to place mean of each group
vals <- pmin(seq(1, by = s + 1, length.out = s), length(vec))
#Assign mean values at those indices
ans[vals] <- tapply(vec, groups, mean)
#Return the final answer
return(ans)
}

apply_fun(vec, 2)
#[1] 4000 NA NA 5000 NA NA NA NA

apply_fun(vec, 3)
#[1] 4000 NA NA NA 5000 NA NA 4500

Tensorflow: Extract Every Other Element

Use slice notation and specify a step of 2 on the second axis you need to extract/sample:

t[:,::2]

Example:

import tensorflow as tf

t = tf.reshape(tf.range(24), (2,6,2))

sess = tf.Session()
print('original: \n', sess.run(t), '\n')
print('every other: \n', sess.run(t[:,::2]))
original:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]]

[[12 13]
[14 15]
[16 17]
[18 19]
[20 21]
[22 23]]]

every other:
[[[ 0 1]
[ 4 5]
[ 8 9]]

[[12 13]
[16 17]
[20 21]]]

How get the element from the vector which is in even positions (2, 4, 6, 8, etc) IN R

We can use seq

winners[seq(2, length(winners), by = 2)]

Or use %%

winners[seq_along(winners) %%2 == 0]

Is there a way to get every n * i element of a vector?

To iterate over every nth element, use .step_by(). However, using that starts at the initial value, you'll need to chain .skip() as well. playground:

let example = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 3;
let result: Vec<_> = example.iter().skip(n-1).step_by(n).copied().collect();
println!("{:?}", result);
[3, 6, 9]

See also:

  • Iterator that returns each Nth value
  • How to iterate over every second number


Related Topics



Leave a reply



Submit