How to Select Elements in a Vector using R

03.24.2021

When using vectors in R, we often want to retrieve an element or a subset of elements from the vector. In this article, we will look some ways to select elements from a vector in R.

The first way we can select an element is using the [] operator and passing the index of the value. Unlike many languages, R start with index 1 rather than 0.

vec = c(1, 2, 3, 4)

v[1]
#> [1] 1

We can also pass a sequence or vector of indexes to retrieve multiple elements.

vec = c(1, 2, 3, 4)

v[1:3]
#> [1] 1, 2, 3

v[c(1, 2, 3)]
#> [1] 1, 2, 3

We can use the - sign to tell which indexes to ignore.

vec[-1] # ignores the first item
#> [1] 2, 3, 4

vec[-(1:3)] # ignores the first three
#> [1] 4

Another way we can select element is using a logical vector or passing a condition.

vec[vec < 4] # select all elements less than 4
#> [1] 1, 2, 3

The final way is a bit more complex. However, R let's you add "names" to vectors which associates a name or key with a value. Let's see an example.

nutrients = c(1, 8, 4)
names(nutrients) = c("fat", "carbs", "protein")
nutrients
#> fat carbs  protein
#>  1    8      4

Above we used the names() function to assign keys to each value. We can now select items based on these names.

nutrients["carbs"]
#> carbs
#> 8

nutrients[c("fat", "protein")]
#> fat protein
#>  1      4