BudiBadu Logo
Samplebadu

R by Example: Vectors

R 4.x

Understanding the fundamental data structure with this sample code demonstrating vector creation using c() function, homogeneous type enforcement, element-wise arithmetic operations, 1-based indexing system, and named vector elements.

Code

# Creating vectors using c() (combine)
numeric_vec <- c(1, 2.5, 4.2)
character_vec <- c("apple", "banana", "cherry")
logical_vec <- c(TRUE, FALSE, TRUE)

// Generating sequences
seq_vec <- 1:10
seq_step <- seq(from = 0, to = 20, by = 2)

# Vector arithmetic (element-wise)
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
sum_vec <- v1 + v2  # 5, 7, 9

# Accessing elements (1-based indexing)
first <- character_vec[1]
subset <- numeric_vec[c(1, 3)]

# Named vectors
scores <- c(Math = 90, English = 85)
math_score <- scores["Math"]

Explanation

Vectors are the most basic data structure in R, representing ordered collections of elements of the same data type. Even a single value in R is technically a vector of length one. Vectors are homogeneous, meaning all elements must be of the same type including numeric, integer, character, logical, complex, or raw. When mixed types are combined using c(), R performs automatic type coercion to the most flexible type, typically converting numbers to characters if any character element is present.

R's vector types and characteristics include:

  • Numeric vectors store decimal numbers with double precision by default
  • Integer vectors require explicit L suffix like 5L for integer storage
  • Character vectors store text strings enclosed in quotes
  • Logical vectors contain TRUE, FALSE, or NA values
  • Named vectors allow element access by name using vec["name"] syntax

Vector arithmetic in R is performed element-wise by default, a feature called vectorization. Operations like c(1, 2) + c(3, 4) produce c(4, 6) by adding corresponding elements. This eliminates explicit loops for many operations and leverages optimized C code underneath for performance. R uses 1-based indexing unlike many languages that start at 0, and supports negative indices to exclude elements, logical vectors for conditional filtering, and index vectors for selecting multiple elements.

Code Breakdown

2
c() function combines elements into homogeneous vector.
7
1:10 colon operator generates integer sequence from 1 to 10 inclusive.
13
v1 + v2 performs element-wise addition, vectorized operation.
16
[1] accesses first element using 1-based indexing system.