R(12), Vector

Published: by Creative Commons Licence

Vector is the most basic data object in R, and it has SIX types of atomic vector: logical, integer, double precision, complex, character, and raw.

we can use charToRaw() to transform a string to Raw class.

create a vector

# Creating a sequence from 5 to 13.
v <- 5:13
# Creating a sequence from 6.6 to 12.6.
v <- 6.6:12.6
# If the final element specified does not belong to the sequence then it is discarded.
v <- 3.8:11.4

seq()

# Create vector with elements from 5 to 9 incrementing by 0.4.
print(seq(5, 9, by = 0.4))

# [1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0

c()

if one of elements in vector is character, then all the other elements will be transfer into character types.

example:

# The logical and numeric values are converted to characters.
s <- c('apple','red',5,TRUE)
print(s)

result:

[1] "apple" "red"   "5"     "TRUE"

visit the elements

# Accessing vector elements using position.
t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
u <- t[c(2,3,6)]
print(u)

# Accessing vector elements using logical indexing.
v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]
print(v)

# Accessing vector elements using negative indexing.
x <- t[c(-2,-5)]
print(x)

# Accessing vector elements using 0/1 indexing.
y <- t[c(0,0,0,0,0,0,1)]
print(y)

results:

[1] "Mon" "Tue" "Fri"
[1] "Sun" "Fri"
[1] "Sun" "Tue" "Wed" "Fri" "Sat"
[1] "Sun"

vector operations

When arithmetic operation is applied to two vectors of unequal length, the elements of the shorter vector are cycled to complete the operation.

example:

v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11)
# V2 becomes c(4,11,4,11,4,11)

add.result <- v1+v2
print(add.result)

sub.result <- v1-v2
print(sub.result)

result:

[1]  7 19  8 16  4 22
[1] -1 -3  0 -6 -4  0

sort(): sort the elements in a vector

both increase and decrease are OK, all we need is to change the value of the parameter.

v <- c(3,8,4,5,0,11, -9, 304)

# Sort the elements of the vector.
sort.result <- sort(v)
print(sort.result)

# Sort the elements in the reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)

# Sorting character vectors.
v <- c("Red","Blue","yellow","violet")
sort.result <- sort(v)
print(sort.result)

# Sorting character vectors in reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)

results:

[1]  -9   0   3   4   5   8  11 304
[1] 304  11   8   5   4   3   0  -9
[1] "Blue"   "Red"    "violet" "yellow"
[1] "yellow" "violet" "Red"    "Blue"