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.

Leave a Reply

Discover more from R Language Frequently Asked Questions

Subscribe now to keep reading and get access to the full archive.

Continue reading