Vector in R Language

A vector in R is a set of numbers. A vector can be considered as a single column or a single row of a spreadsheet. The following examples are numbers that are not technically “vectors”. It is because these vectors are not in a column/row structure, however, they are ordered. These vectors can be referred to by index.

Creating Vector in R

# Creating a vector with the c function

c(1, 4, 6, 7, 9)

c(1:5, 10)
Creating Vector in R Language

A vector in R language can be created using seq() function, it generates a series of numbers.

# Create a vector using seq() function

seq(1, 10, by = 2)
seq(0, 50, length = 11)
seq(1, 50, length = 11)
Creating Vector in R using seq() Function

The vector can be created in R using the colon (:) operator. Following are the examples

# Create vector using : operator

1:10

## Output
[1]  1  2  3  4  5  6  7  8  9 10

5:1

## Output
[1] 5 4 3 2 1

The non-integer sequences can also be created in R Language.

# non-integer sequences
seq(0, 100*pi, by = pi)
Non integer vector in R

One can assign a vector to a variable using the assignment operator (<-) or equal symbol (=). The examples are:

a <- 1:5
b <- seq(15, 3, length=5)
c <- a * b

There are a lot of built-in functions that can be used to perform different computations on vectors. For example,

a <- 1:5

# compute the total of elements of a vector
sum(a)

## Output
15

# product of elements of a vector
prod(a)

## Output
120

# average of the vector
mean(a)

## Output
3

# standard deviation and variance of a vector
sd(a)

## Output 
1.581139

var(a)

## Output
2.5

One can extract the elements of a vector by using square brackets and the index of the component of the vector.

V <- seq(0, 100, by = 10)
V[] # gives all the elements of the vector

## Output
[1]   0  10  20  30  40  50  60  70  80  90 100

V[5] # 5th elements from vector z

## Output
[1] 40

V[c(2, 4, 6, 8)] #2nd, 4th, th, and 8th element

## Output
[1] 10 30 50 70

V[-c(2, 4, 6, 8)] # elements except 2nd, 4th, 6th, and 8th element

## Output
[1]   0  20  40  60  80  90 100

The specific / required elements of a vector can be updated

V[c(2, 4)] <- c(500, 600) # the second and 4th element is updated to 500 and 600
Updating vector elements in R

https://itfeature.com

https://gmstat.com

The important points about vectors in R language are:

  • Data Types: Vectors can hold logical, integer, double, character, complex, or raw data.
  • Creation: Use the c() function to combine elements into a vector.
  • Accessing Elements: Use indexing (square brackets) to access individual elements.
  • Vector Operations: Perform arithmetic, logical, and comparison operations on vectors.
  • Vectorization: R excels at vectorized operations, making calculations efficient.

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

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