R is primarily a programming language for data manipulation, and its fundamental data structure is the vector. Unlike other languages where primitive data types may include scalars, R’s primary focus is on vectors. Understanding how to work with vectors is crucial for effective programming and reading R code.
In this tutorial, you will learn about various operations involving vectors in R. Specifically, you will discover:
- The fundamental data objects in R.
- How to manipulate vectors in R.
Let’s get started!
Overview
This tutorial is divided into three parts:
- Fundamental Data Objects
- Operations on Vectors
- From Vector to Matrix
Fundamental Data Objects
In other programming languages like Python, you work with basic data types such as integers, floats, and strings. In R, however, the primary data objects include vectors, lists, factors, data frames, and environments. R recognizes several data types, such as character, numeric, integer, logical, and complex, but natively handles vectors of integers rather than single integers.
To create a simple vector of integers ranging from 5 to 10, you can simply use:
x <- 5:10
This compact syntax generates a sequence of consecutive integers. You can also use the seq()
function to create more complex numeric sequences:
y <- seq(from = 2, to = 10, by = 1)
For an arbitrary sequence, utilize the c()
function:
y <- c(2, 3, 5, 8, 13, 21, 34)
You can access elements in a vector using indices. For instance, to retrieve the first element:
print(x[1]) # Output: 5
Keep in mind that R uses 1-based indexing. You can extract multiple elements from a vector as well:
print(x[1:5]) # Returns a vector: [1] 5 6 7 8 9
This works because 1:5
corresponds to the indices you want to access. Alternatively, you can specify non-sequential indices:
print(x[c(2, 3, 5)]) # Returns: [1] 6 7 9
To update an element within a vector, you can simply assign a new value:
x[4] <- 42
If you wish to insert new elements without overwriting existing ones, use the append()
function:
x <- append(x, 101)
You can also insert elements at specific positions:
x <- append(x, -1, after = 0) # Insert -1 at the beginning
To remove an element from a vector, apply negative indexing:
x <- x[-3] # Remove the third element
Negative indices indicate the elements you wish to remove from the vector.
Operations on Vectors
In R, vector operations are primarily applied element-wise. For example:
c(10, 9, 8, 7) %/% 3
# Output: [1] 3 3 2 2
Here, %/%
denotes integer division (the result of which discards the remainder), while %%
provides the remainder:
c(10, 9, 8, 7) %% 3
# Output: [1] 1 0 2 1
Beyond basic arithmetic, R supports a suite of mathematical functions. For instance, the exponential and logarithmic functions can be applied like this:
exp(x)
log(x)
You can find a comprehensive list of built-in functions through R’s help system:
library(help = "base")
From Vector to Matrix
Vectors can be converted into matrices in R. For example, you can create a matrix filled with values from a vector:
A <- matrix(c(9, 5, 4, 2, -1, 0, 1, 6, -2), ncol = 3)
print(A)
This constructs a matrix by filling values column-wise. You can explicitly change this behavior by using the byrow
parameter:
A <- matrix(c(9, 5, 4, 2, -1, 0, 1, 6, -2), ncol = 3, byrow = TRUE)
To retrieve the dimensions of a matrix, use:
dim(A)
This will return the number of rows and columns:
[1] 3 3
In a square matrix, you can calculate its determinant and inverse:
det(A) # Calculate determinant
solve(A) # Calculate inverse
To extract specific rows, columns or elements, use indexing:
# Accessing the first column
print(A[, 1])
# Accessing the second row
print(A[2, ])
# Accessing a specific element
print(A[3, 2])
To combine two matrices, you can use cbind()
for column-wise binding or rbind()
for row-wise binding:
cbind(A, A.inv) # Adds columns
rbind(A, A.inv) # Adds rows
Conclusion
In this tutorial, you explored the operations associated with vectors and arrays in R. Specifically, you learned how to:
- Create and manipulate vectors.
- Utilize vectors as sets.
- Work with multi-dimensional arrays in R.
Further Reading
For additional insights on vectors and data manipulation in R, consider the following resources:
Websites:
Books:
- The Book of R: A First Course in Programming and Statistics
- R for Data Science: Import, Tidy, Transform, Visualize, and Model Data
Feel free to reach out if you need further modifications or additional information!