Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

algorithm - How does this odds/even extraction work in R language?

> 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...