R Tutorial R Charts & Graphs R Statistics R References

R - Colon operator



In R, the colon operator : is used to generate regular sequences. It is a binary operator and used as a:b, which generates a sequence from a to b in steps of 1 or -1.

Example:

In the example below, a for loop is used to display content of the sequence.

for (i in 5:10){
  print(i)
}

The output of the above code will be:

[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Example:

In the example below, the colon operator is used to generate sequences which is further converted into a vector.

v1 <- 1:5
v2 <- 1.2:5
v3 <- 1:-5
v4 <- 1.2:-5

#displaying vectors
print(v1)
print(v2)
print(v3)
print(v4)

The output of the above code will be:

[1] 1 2 3 4 5
[1] 1.2 2.2 3.2 4.2
[1]  1  0 -1 -2 -3 -4 -5
[1]  1.2  0.2 -0.8 -1.8 -2.8 -3.8 -4.8

Example:

In the example below, the colon operator is used to create a sequence which is further converted into a matrix.

m1 <- matrix(1:9, nrow=3)

#displaying matrix
print(m1)

The output of the above code will be:

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

❮ R - Operators