Extract Every Nth Element of a Vector

Extract every nth element of a vector

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

Extract every nth element of an array

Try

my.array[,,seq(1,360,3)]

which has

> dim(my.array[,,seq(1,360,3)])
[1] 54 71 120

Create a vector where a function is applied to every nth element

To functionalize the comment from @qdread for any n:

# create function X to extract first element from vector y
X <- function(y) y[1]

# create function to apply function X to nth element of vector v
my_fn <- function(v, n) {
sapply(v, function(i) if (i%%n == 0) X else 0)
}

MATLAB: extract every nth element of vector

Try this:

x = linspace(1, 10, 10);
n = 3;
y = x(1 : n : end); % => 1 4 7 10
y = x(n : n : end); % => 3 6 9

extract every nth element of a column in a dataset

Just use seq to create a sequence of the numbers you want, and use [seq,] for indexing. Aditionally, to select a given oclumn, use [,"col_name"]

df <- iris
row_seq <- seq(5, nrow(df), by=5)
df[row_seq,]
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 5 5.0 3.6 1.4 0.2 setosa
#> 10 4.9 3.1 1.5 0.1 setosa
#> 15 5.8 4.0 1.2 0.2 setosa
#> 20 5.1 3.8 1.5 0.3 setosa
...

Created on 2022-05-22 by the reprex package (v2.0.1)

How delete every 3rd Element of a vector?

You can use a sequence as the index

myList[-c(3*1:5)]

[1] 1 2 4 5 7 8 10 11 13 14

You can use sequencing functions to make it consistent with any vector lengths with this:

myList[seq_along(myList)%%3!=0]

and this (credit to @thelatemail for that):

myList[-seq(3, length(myList), 3)]


Related Topics



Leave a reply



Submit