Vectors - Part 1

Introduction

In the previous post, we learnt about the basic data types in R. IN this post, we will:

  • understand the concept of vectors
  • learn to create vectors of different data types

Vectors

Vector is the most basic data structure in R. It is a sequence of elements of the same data type. If the elements are of different data types, they will be coerced to a common type that can accommodate all the elements. Vectors are generally created using c() (concatenate function), although depending on the data type of vector being created, other methods can be used.

Numeric Vector

We will create a numeric vector using c() but you can use any function that creates a sequence of numbers. After that we will use is.vector() to check if it is a vector and class to check the data type.

# create a numeric vector
num_vect <- c(1, 2, 3)

# display the vector
num_vect
## [1] 1 2 3
# check if it is a vector
is.vector(num_vect)
## [1] TRUE
# check data type
class(num_vect)
## [1] "numeric"

Let us look at other ways to create a sequence of numbers. We leave it as an exercise to the reader to understand the functions using help.

# using colon
vect1 <- 1:10
vect1
##  [1]  1  2  3  4  5  6  7  8  9 10
# using rep
vect2 <- rep(1, 5)
vect2
## [1] 1 1 1 1 1
# using seq
vect3 <- seq(10)
vect3
##  [1]  1  2  3  4  5  6  7  8  9 10

Integer Vector

Creating an integer vector is similar to numeric vector except that we need to instruct R to treat the data as integer and not numeric or double. We will use the same methods we used for creating numeric vectors. To specify that the data is of type integer, we suffix the number with L.

# integer vector
int_vect <- c(1L, 2L, 3L)
int_vect
## [1] 1 2 3
# check data type
class(int_vect)
## [1] "integer"
# using colon
vect1 <- 1L:10L
vect1
##  [1]  1  2  3  4  5  6  7  8  9 10
# using rep
vect2 <- rep(1L, 5)
vect2
## [1] 1 1 1 1 1
# using seq
vect3 <- seq(10L)
vect3
##  [1]  1  2  3  4  5  6  7  8  9 10

Character Vector

A character vector may contain a single character, a word or a group of words. The elements must be enclosed in single or double quotations.

# character vector
greetings <- c("hello", "good morning")
greetings
## [1] "hello"        "good morning"
# check data type
class(greetings)
## [1] "character"

Logical Vector

A vector of logical values will either contain TRUE or FALSE or both.

# logical vector
vect_logic <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
vect_logic
## [1]  TRUE FALSE  TRUE  TRUE FALSE
# check data type
class(vect_logic)
## [1] "logical"

In fact, you can create an integer vector and coerce it to type logical.

# integer vector
int_vect <- rep(0L:1L, 3)
int_vect
## [1] 0 1 0 1 0 1
# coerce to logical vector
log_vect <- as.logical(int_vect)
log_vect
## [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE
# check data type
class(log_vect)
## [1] "logical"