Operations on Vectors in R



Vectors are fundamental data structures in R, forming the building blocks for data manipulation and analysis. Beyond basic vector operations found in textbooks, R supports a wide range of advanced functionalities. In this tutorial, you will learn:

  • How to manipulate vectors.
  • How to treat vectors as sets.

Let’s get started!

Overview

This tutorial consists of three main sections:

  1. Reading and Modifying a Vector
  2. Vectors as Sets
  3. Arrays in R

Reading and Modifying a Vector

Creating a simple integer vector in R is straightforward:

x <- 2:100

This creates a sequence of consecutive integers from 2 to 100. You can generate more complex vectors using the seq() function for an arithmetic progression:

y <- seq(from = 2, to = 100, by = 1)

Or, for an arbitrary sequence of numbers, utilize the c() function:

y <- c(2, 3, 5, 8, 13, 21, 34)

To access individual elements in a vector, simply provide the index:

print(x[1])  # Access the first element

Remember, R uses 1-based indexing, meaning that the first element is indexed at 1.

You can also retrieve multiple elements with a similar syntax:

print(x[1:5])  # Access the first five elements

This returns a new vector consisting of the specified elements. You can also use the c() function to select non-sequential indices:

print(x[c(2, 3, 5, 7)])

To update elements within a vector, assign new values directly:

x[4] <- 42
x[4:5] <- c(42, 43)

If you wish to insert new elements rather than overwrite existing ones, utilize the append() function:

x <- append(x, 101)
x <- append(x, c(102, 103))

The append() function not only adds elements to the end of a vector but can also insert them in the middle:

x <- append(x, -1, after = 0)  # Insert at the beginning

Since R vectors are immutable, inserting elements creates a new object, so remember to assign it back to the original variable.

To remove elements from a vector, use negative indexing:

x <- x[-3]  # Remove the third element

You can remove multiple elements similarly:

x <- x[-c(2, 4, 6, 8)]  # Remove specific elements
x <- x[-(2:5)]          # Remove a range of elements

Negative indices are treated as removal requests in R.

Vectors as Sets

In R, vectors serve as fundamental data objects, and as ordered tuples, the sequence of their elements matters. However, we can also treat vectors as sets.

Consider the following:

w <- c("apple", "banana", "cantaloupe")
x <- c("apple", "banana", "cantaloupe")
y <- c("banana", "pear", "tangerine")
z <- c("cantaloupe", "banana", "apple")

You can check if two vectors are identical:

identical(w, x)  # Returns TRUE

However, x and z are not identical, though they represent the same set:

setequal(x, z)  # Returns TRUE

This means setequal() shows TRUE for vectors of different sizes as long as their unique elements match perfectly, given that sets do not consider duplicates.

You can create new vectors through set operations such as intersection and union:

intersect(x, y)
union(x, y)

Additionally, you can find the set difference:

setdiff(x, y)  # Elements in x not in y
setdiff(y, x)  # Elements in y not in x

To check membership in a set, you would use:

"apple" %in% x  # Returns TRUE

While R does not have a built-in “not in” operator, you can express this with:

!("apple" %in% x)  # Returns FALSE

Arrays in R

You may recall from previous discussions how vectors can be converted into matrices; matrices are two-dimensional data structures. For higher dimensions, you would use arrays.

You can convert a vector into an array by specifying its dimensions explicitly:

x <- array(2:25, dim = c(3, 2, 4))  # Create a 3D array

In R, an array fills along the first dimension, followed by the second, and so on. For instance, x[, 1, 1] would yield the first three values: c(2, 3, 4).

Similar to vector indexing, you can extract a 2D array from a 3D array:

x[c(1, 2), c(1, 2), 1]

To convert an array back to a vector, use the following:

as.vector(x)

Conclusion

In this tutorial, you learned about the various operations on vectors and arrays in R. Specifically, you covered:

  • How to create and manipulate vectors.
  • The treatment of vectors as sets.
  • The use of multi-dimensional arrays in R.

Further Reading

For additional resources on the topics covered, consider the following:

Websites:

Books:

  • The Book of R: A First Course in Programming and Statistics

Feel free to reach out if you need any further modifications or information!

Leave a Comment