Creating Vectors in R, Subsetting, and Vectorization

The article is about creating vectors in R language. You will also learn about quick and short methods of subsetting the vectors in R and the vectorization of vectors

Creating Vectors in R Using c() Function

The c() function can be used for creating vectors of objects in R. This function concatenates the values having one dimension (either row or column matrix in a sense). The following are some examples related to creating different types of vectors in R.

# Numeric vector
x <- c(1, 2, 5, 0.5, 10, 20, pi)
# Logical vector
x <- c(TRUE, FALSE, FALSE, T, T, F)
# Character vector
x <- c("a", "z", "good", "bad", "null hypothesis")
# Integer vector 
x <- 9 : 29   # (colon operator is used)
x <- c(1L, 5L, 0L, 15L)
# Complex vector
x <- c(1+0i, 2+4i, 0+0i)

Using vector() Function

Creates a vector of $n$ elements with a default value of zero for numeric vector, an empty string for character vector, FALSE for logical vector, and 0+0i for complex vector.

# Numeric vector of lenght 10 (default is zero)
x <- vector("numeric", length = 10)
# Integer vector of length 10 (default is integer zeros)
x <- vector("integer", length = 10)
# Character vector of length 10 (default is empty string)
x <- vector("character", length = 10)
# Logical vector of length 10 (default is FALSE)
x <- vector("logical", length = 10)
# Complex vector of length 10 (default is 0+0i)
x <- vector("complex", length=10)
Vectors in R

Creating Vectors with Mixed Objects

When different objects are mixed in a vector, coercion occurs, that is, the data type of the vector changes intelligently.

The following are examples

# coerce to character vector 
y <- c(1.2, "good")
y <- c("a", T)
# coerce to a numeric vector
y <- c(T, 2)

From the above examples, the coercion will make each element of the vector of the same class.

Explicitly Coercing Objects to Other Class

Objects can be explicitly coerced from one class to another class using as.character(), as.numeric(), as.integer(), as.complex(), and as.logical() functions. For example;

x <- 0:6
as.numeric(x)
as.logical(x)
as.character(x)
as.complex(x)

Note that non-sensual coercion results in NAs (missing values). For example,

x <- c("a", "b", "c")
as.numeric(x)
as.logical(x)
as.complex(x)
as.integer(x)

Vectorization in R

Many operations in the R Language are vectorized. The operations ( +, -, *, and / ) are performed element by element. For example,

r vectors
x <- 1 : 4
y <- 6 : 9

# Arithmetics
x + y
x - y
x * y
x / y
# Logical Operation
x >= 2
x < 3
y == 8

Without vectorization (as in other languages) one has to use a for loop for performing element-by-element operations on say vectors.

Subsetting Vectors in R Language

Subsetting in the R Language can be done easily. Subsetting vectors means extracting the elements of a vector. For this purpose square brackets ([ ]) are used. For example;

x <- c(1, 6, 10, -15, 0, 13, 5, 2, 10, 9)

# Subsetting  Examples
x[1]   # extract first element of x vecotr
x[1:5] # extract first five values of x
x[-1]  # extract all values except first
x[x > 2] # extracts all elements that are greater than 2

head(x)  # extracts first 6 elements of x
tail(x)  # extracts last 6 elements of x

x[x > 5 & x < 10]  # extracts elements that are greater than 5 but less than 10

One can use the subset() function to extract the desired element using logical operators, For example,

subset(x, x > 5)
subset(x, x > 5 & x < 10)
subset(x, !x < 0 )

Learn more about Vectors

https://itfeature.com

https://gmstat.com

Lists in R Language: Create, Name, and Append

Before understanding and working on lists in R Language, let’s review the other data types in R Language.

Each of the data types (vectors, matrices, and data frames) has some level of constraints. For example, vectors are single-column data types and can only store one type of data. Matrices are of two-dimensional, but they can store only one type of data. On the other hand, data frames are two-dimensional and can store different types of data, but in data frames, the length of columns should be the same.

Lists in R Language

Lists in R are a fundamental data structure used to store collections of elements. Lists offer a flexible way to organize data of different types, unlike vectors that can hold elements of the same data type. Lists in R language have no such constraints as vectors, matrices, and data frames. The element of a list can contain any type of data can contain any type of data having varying lengths for each element.

Lists are the most flexible data type in R, as the list can hold all kinds of different operations when programming. Let us consider some examples of how to create lists in R, and how elements of the list can be named, retrieved, and appended. The list data type is created using the list() keyword. For examples,

mylist <- list('alpha', 'beta', 'gamma', 1:5, TRUE)

Note that lists are printed differently and they have their form of indexing for retrieving each element of the list.

Retrieving List Elements

A certain element of a list can be accessed using the subsetting technique (based on the list indexing mechanism. For example, to access the first three elements of the list created above, one can write in R console as,

A certain element of a list can be accessed using a subsetting technique (based on the list indexing mechanism. For example, to access the first three elements of the list created above, one can write in R console as,

mylist[1:3]

To examine one element of the list, double square brackets can be used with the required index number. For example, to access the fourth element of the list, one can use,

mylist[[4]]

Note when one uses normal subsetting, a list will be obtained as a result. When double square brackets are used the contents of the elements are obtained. Note the difference and command and output of each command used below:

mylist[4]
mylist[[4]]

Naming Elements of a List

The elements of a list can be named, and elements of lists can be retrieved using the $ operator instead of square brackets. The first command will name the elements of the mylist object. and then other commands will result in the same output.

names(mylist) <- c("a", "b", "c", "d", "e")

mylist$d
myslit[[4]]
Lists in R Language: Create, Name, and Append

Appending an Element to List

Like data frames, an element of a list can be created by assigning something to an index that does not exist yet. For example, a sixth element is added to the list

mylist$f <- c("Pass", "Fail")

Now the 6th element of the list contains a vector of strings “Pass”, and “Fail”. To check this,

mylist$f
mylist[[6]]

To access the elements of specific list vector subsetting and two square brackets can be used. For example to access the fourth element of the list one can use,

mylist[[4]][3] # 3rd element of 4th list element
mylist[[4]][1:3]# first three elements of 4th list element
mylist$d[3]
  • Remember to name elements for readability when dealing with complex data structures.
  • Lists are versatile for storing various data types, making them a powerful tool for data organization in R.

For further reading about lists see the link Lists in R.

MCQs General Knowledge

Vectors in R Language

Introduction to Vectors in R Language

Vectors in the R Language are the simplest data structures. A vector in R is also an object containing elements of the same data type. To create a vector (say ‘x’) of the same type (that is data type is double) of elements consisting of five elements one can use the c() function. For example,

Creating Vectors in R using the c() Function

x <- c(10, 7, 3, 2, 1)

The c() function can be used to combine a different number of vectors into a single vector. A single number is regarded as a vector of length one. For example, a vector (say ‘y’) is created by combining the existing vector(s) with a single number.

Appending a Number to an Existing Vector(s)

One can append a number to an existing vector or even append a vector with another vector. For example, vectors in R Language can be appended like:

y <- c(x, .55)
z <- c(x, y)
Vectors in R Language

Extracting Vector Element(s)

The simplest example to select a particular element of a vector can be performed by using a subscription mechanism. That is, use the name of the vector with a square ([ ]) bracket with a number in it indicating the position of a vector element. For example,

# shows first element of vector x
> x[1:2]   # shows first two elements of vector 'x'
> x[3:5]   # shows elements of vector 'x' from index 3 to 5

Note that a positive number is used as a subscript index in a square bracket. A positive subscript indicates the index (position) of a number to extract from the vector. A negative number as the index can also be used, which is used to select all the elements except the number(s) that are used in the square bracket ([ ]).

An example of a negative index is;

x[-1]       # shows all elements of vector 'x' except first element
x[-(1:2)]   # shows elements of vector 'x' except first two elements

Also note that if the number exceeds the number of elements in a vector, then it will result in NA (not available). For example,

x[7] 
x[1:10]

Updating Vector Elements

One or more elements of a vector can be changed by the subsetting mechanism. For example, to change the 4th element of a vector, one can proceed as follows;

x[4] <- 15     # 4th position of vector 'x' is updated to 15
x[1:3] <- 4    # first three numbers are updated to 4
x[1:3] <- c(1,2,3) # first three numbers are updated to 1, 2, and 3

Learn about R Workspace, Objects, and .RData File

Online Multiple Choice Questions Quiz Preparation Website