Index searches on an R vector

3

In RStudio how to choose elements of a vector that are in odd or even positions?

    
asked by anonymous 01.11.2017 / 10:22

2 answers

4

You can create two indexes that identify even and odd positions

x <- rnorn(1500)
par <- (1:length(x) %% 2) == 0 
impar <- (1:length(x) %% 2) != 0 

Then just call the vector with these indexes

x[par]
x[impar]
    
01.11.2017 / 15:41
2

One way is to take advantage of the recycling that happens automatically in R. Example:

x <- 1:15
x[c(TRUE, FALSE)] # retorna os ímpares
x[c(FALSE, TRUE)] # retorna os pares

Remembering that indexes start from 1 in R.

    
01.11.2017 / 17:21