Vectors in R

Get familiar with the concept of vectors in R.

Since R is an object-oriented programming language, it’s helpful to know how R works with data. A simplified view is that R relies on various functions, which take in data as input and then produce the desired output objects.

In other words, R treats data as objects and operates on them through functions (which are themselves treated as objects) to manipulate data, create graphs, and conduct statistical analysis.

Create a vector using c() Function

The most basic data object in R is a vector. A vector is a combination of elements, such as numbers, characters, or logical statements. The elements within a single vector must be of the same type: numeric, character, or logical.

The first function is c(). The c() function combines or concatenates the terms or arguments inside the parentheses together into a vector. For example, the R code below creates a vector that contains some arbitrary numbers, separated by commas, inside a pair of parentheses.

Press + to interact
c(1, 2, 0, 2, 4, 5, 10, 1)

To save the vector for later use, we assign it to an R object with an arbitrary name. R uses the assignment symbol <- (a less than symbol followed by a minus sign, with no space in between) to link the name of the object, v1, and the c() function. Then, in a new line of code, we type the object name given to the vector, which simply displays what is in that object. The R code is as follows:

Press + to interact
v1 <- c(1, 2, 0, 2, 4, 5, 10, 1)
v1

R works with various objects, such as numeric, logical, character, list, matrix, array, factor, or data frame. Different objects have different attributes. Even though we won’t go into details about all their differences in this introductory course, it’s always a good idea to know what type of object we’ve created.

Identifying object’s type in R

To identify the object type of v1, we simply apply the class() function.

Press + to interact
class(v1)

Collecting these four lines of code, along with explanatory comment lines that are ignored in execution, we produce the following R program:

Press + to interact
# use c() function to create a vector object
c(1, 2, 0, 2, 4, 5, 10, 1)
# assign the c function output to an object named v1
v1 <- c(1, 2, 0, 2, 4, 5, 10, 1)
# call object v1 to see what is in it
v1
# identify object type of v1
class(v1)