1
> a <- sample(c(1:10), 20, replace = TRUE)
> a
 [1]  6  3  6  2  6  9  3  9  9  8  2 10  7  9  1  5  3 10  5  5
> a[c(TRUE,FALSE)]
 [1] 6 6 6 3 9 2 7 1 3 5

Why a[c(TRUE,FALSE)] gives me an ODD elements of my array? c(TRUE, FALSE) has length of 2. And on my mind, this supposed to give me a single index 1, which is TRUE.

Why is this comes by this way?

zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

2

Logical subsets are recycled to match the length of the vector (numerical subsets are not recycled).

From help("["):

Arguments

i, j, …

...

For [-indexing only: i, j, can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. i, j, can also be negative integers, indicating elements/slices to leave out of the selection.

When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.


To illustrate, try:

cbind.data.frame(x = 1:10, odd = c(TRUE, FALSE), even = c(FALSE, TRUE))
#     x   odd  even
# 1   1  TRUE FALSE
# 2   2 FALSE  TRUE
# 3   3  TRUE FALSE
# 4   4 FALSE  TRUE
# 5   5  TRUE FALSE
# 6   6 FALSE  TRUE
# 7   7  TRUE FALSE
# 8   8 FALSE  TRUE
# 9   9  TRUE FALSE
# 10 10 FALSE  TRUE
zx8754
  • 52,746
  • 12
  • 114
  • 209
khoffmann
  • 173
  • 5
0

a[TRUE] gives your all the elements and a[FALSE] gives none. for a[c(TRUE,FALSE] it will wrap length(c(TRUE,FALSE)) which is 2 to length(a) which is 20, so for example it would be like TRUE, FALSE, TRUE, .... , then it will give you just odds indexes.

Ehsan Gerayli
  • 495
  • 2
  • 9