Index searches on an R vector

Asked

Viewed 830 times

3

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

  • Rstudio is just your IDE, you want to refer to R language?

2 answers

5

You can create two indices 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]

2

One way is to take advantage of recycling which happens automatically on the 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.

  • Thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.