Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract every element except every n-th element of vector

Given a vector

A = [1,2,3,...,100]

I want to extract all elements, except every n-th. So, for n=5, my output should be

B = [1,2,3,4,6,7,8,9,11,...]

I know that you can access every n-th element by

A(5:5:end)

but I need something like the inverse command. If this doesn't exist I would iterate over the elements and skip every n-th entry, but that would be the dirty way.

like image 238
Thomas Avatar asked Nov 20 '12 09:11

Thomas


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 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 I select only part of a vector in R?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.

How do I get 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).


4 Answers

You can eliminate elements like this:

A = 1:100;
removalList = 1:5:100;
A(removalList) = [];
like image 52
HebeleHododo Avatar answered Oct 23 '22 18:10

HebeleHododo


Use a mask. Let's say you have

A = 1 : 100;

Then

m = mod(0 : length(A) - 1, 5);

will be a vector of the same length as A containing the repeated sequence 0 1 2 3 4. You want everything from A except the elements where m == 4, i.e.

B = A(m ~= 4);

will result in

B == [1 2 3 4 6 7 8 9 11 12 13 14 16 ...]
like image 28
Mehrwolf Avatar answered Oct 23 '22 20:10

Mehrwolf


Or you can use logical indexing:

n = 5; % remove the fifth
idx = logical(zeroes(size(A))); % creates a blank mask
idx(n) = 1; % makes the nth element 1
A(idx) = []; % ta-da!

About the "inversion" command you cited, it is possible to achieve that behavior using logical indexing. You can negate the vector to transform every 1 in 0, and vice-versa.

So, this code will remove any BUT the fifth element:

negatedIdx = ~idx;
A(negatedIdx) = [];
like image 35
Castilho Avatar answered Oct 23 '22 20:10

Castilho


why not use it like this?

say A is your vector

A = 1:100
n = 5
B = A([1:n-1,n+1:end])

then

B=[1 2 3 4 6 7 8 9 10 ...]
like image 41
Vasco Avatar answered Oct 23 '22 20:10

Vasco