R Tutorial



R VECTORS


Vectors in R

A vector is the most basic data structure in R. It is a sequence of elements that are all of the same type. Vectors can store numeric values, characters, logical values, or other types, but all elements in a single vector must be of the same type.

Creating Vectors

Use the c() function to combine values into a vector.

# Numeric vector
numbers <- c(10, 20, 30, 40, 50)

# Character vector
fruits <- c("apple", "banana", "cherry")

# Logical vector
flags <- c(TRUE, FALSE, TRUE, TRUE)
  

Vector Types

  • Numeric vectors: Contain numbers (e.g., 1, 2.5, -3).
  • Character vectors: Contain text (strings).
  • Logical vectors: Contain TRUE or FALSE values.

Accessing Vector Elements

Use square brackets [] with the index (starting at 1) to access elements.

fruits[2]        # "banana"

numbers[c(1, 3)]  # selects 1st and 3rd elements: 10 and 30

flags[flags == TRUE] # elements where value is TRUE
  

Vector Operations

Vectors support arithmetic and logical operations element-wise.

a <- c(2, 4, 6)
b <- c(1, 3, 5)

a + b          # adds elements: c(3, 7, 11)
a * 2          # multiplies each element by 2: c(4, 8, 12)
a > 3          # logical comparison: c(FALSE, TRUE, TRUE)
  

Important Vector Functions

  • length(x) – returns number of elements
  • sum(x) – sums numeric elements
  • mean(x) – calculates average
  • sort(x) – sorts elements
  • unique(x) – returns unique elements

Summary

  • Vectors hold elements of the same type.
  • Use c() to create vectors.
  • Access elements with square brackets [].
  • Vectors support element-wise operations.
  • Functions like length(), sum(), and mean() help analyze vectors.

Practice Exercises

  • Create a numeric vector with 5 values and find its sum and mean.
  • Create a character vector of your 3 favorite cities.
  • Access the 2nd element of any vector.
  • Create two numeric vectors and perform element-wise addition.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review