Vectors

Vectors

Vectors

Vectors are one of the most basic and important data structures in R. A vector is an ordered collection of values of the same data type, such as numbers, characters, or logical (TRUE/FALSE) values.

In statistics and data science, vectors are commonly used to store data observations, variables, or results of calculations.

Key Characteristics of Vectors

  • One-dimensional: Vectors have length but no rows or columns.

  • Homogeneous: All elements must be the same data type.

  • Ordered: Each element has a specific position (index).

  • Indexed starting at 1: R uses 1-based indexing (not 0).

Creating Vectors in R

The most common way to create a vector is using the c() (combine) function.


# Numeric vector

scores <- c(88, 92, 79, 85)


# Character vector

names <- c("Alex", "Jordan", "Taylor")


# Logical vector

passed <- c(TRUE, TRUE, FALSE, TRUE)


Vector Length

Use length() to find how many elements are in a vector.


length(scores)

Accessing Elements in a Vector

You can access elements using square brackets [ ].


scores[1]      # First element

scores[2:4]    # Elements 2 through 4

scores[-1]     # All elements except the first


Vectorized Operations

One of R’s strengths is that operations are vectorized, meaning they automatically apply to every element in a vector.


scores + 5

scores * 1.1


This is much faster and cleaner than using loops.

Common Statistical Functions with Vectors

Vectors are the foundation of statistical analysis in R.


mean(scores)

median(scores)

sd(scores)

summary(scores)

favstats(scores)


Type Coercion

If you mix data types in a vector, R will coerce all elements to the most flexible type.


mixed <- c(1, 2, "three")

mixed


Result: everything becomes a character vector.

Logical Vectors and Filtering

Logical vectors are often used to filter data.


scores[scores >= 85]


This returns only the values that meet the condition.

Common Pitfalls

  • ❌ Trying to store different data types in one vector

  • ❌ Forgetting that indexing starts at 1

  • ❌ Confusing vectors with data frames or matrices


Why Vectors Matter

Almost everything in R is built on vectors:

  • Columns in data frames are vectors

  • Statistical models operate on vectors

  • Many R functions expect vector input


Understanding vectors is essential for working effectively with data in R.