Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select every other element from a vector

Tags:

r

vector

seq

Let's say I had a vector:

remove <- c(17, 18, 19, 20, 24, 25, 30, 31, 44, 45).

How do I select / extract every second value in the vector? Like so: 17, 19, 24, 30, 44

I'm trying to use the seq function: seq(remove, 2) but it doesn't quite work.

Any help is greatly appreciated.

like image 443
user1313954 Avatar asked Nov 19 '12 20:11

user1313954


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 values 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 extract odd numbers from a vector in R?

To find the position of odd numbers in an R vector, we can find the position of values that are divisible by 2 with the help of which function. For example, if we have a vector called x then we can find the position of odd numbers using the command which(x%%2==1).


2 Answers

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.

like image 76
Sven Hohenstein Avatar answered Sep 22 '22 12:09

Sven Hohenstein


remove[seq(1,length(remove),2)] 
like image 33
Grega Kešpret Avatar answered Sep 23 '22 12:09

Grega Kešpret