# Selecting elements by slicing


Find this notebook on the web at
<a class="quarto-xref" href="https://resampling-stats.github.io/edition-3-r/more_sampling_tools.html#nte-selecting_by_slicing">Note <span>10.1</span></a>.

As you saw in <a class="quarto-xref" href="https://resampling-stats.github.io/edition-3-r/resampling_with_code2.html#sec-array-indexing"><span>Section 6.6</span></a>, we do
*indexing* when we put square brackets following a value that is a
container, such as a vector. Inside the square brackets we put another
value to specify which elements we want to fetch from the container.

We will use the `some_numbers` vector as our container for indexing:

```{r}
some_numbers = c(3, 1, 4, 1, 5, 9, 2, 6)
```

In the indexing expression below, we have the vector `some_numbers`,
followed by the value `3` inside the square brackets, telling R that we
want the third value from the `some_numbers` container.

```{r}
# Indexing with an integer inside the square brackets.
some_numbers[3]
```

In the example above, we put an integer (a whole number) inside the
square brackets, to specify the position of the element we want to fetch
from the container.



We can also put a *vector* inside the square brackets. If we put a
vector inside the square brackets, the elements of that vector specify
the positions of the elements we want to fetch.

We have already seen that R can form a vector of sequential integers by
using the colon (`:`) operator.

```{r}
# The sequence of integers from 3 through 8
3:8
```

See <a class="quarto-xref" href="https://resampling-stats.github.io/edition-3-r/testing_counts_2.html#nte-what-is-an-operator">Note <span>23.2</span></a> for
more on operators. The colon operator (the `:`) serves as a signal to R
to create a new value by *operating* on the values to the left and right
of the colon.

The integer to the left of the colon specifies the *start* position;
this is the position of the first element we want. The integer to the
right of the colon gives the *stop* position. R interprets this as
asking for a vector containing all the integers from (including) the
*start* value (3 in the example above) through (including) the stop
value (8 in the example above).

For example, here we index the vector `some_numbers` with another vector
having *start* position of 2 and *stop* position of 5. The result is
another vector, that has the elements of `some_numbers` from positions 2
through 5:

```{r}
# Indexing a vector with a vector.
our_positions <- 2:5
some_numbers[our_positions]
```

Of course we could also do the same thing in one line, by forming the
vector of positions inside the square (indexing) brackets:

```{r}
# Indexing a vector with a vector.
some_numbers[2:5]
```

