Vectors
Vectors
WHAT IS VECTOR ?
Example:
class(myname)
[1] “character”
Both class() and typeof() appear to return very similar outputs on some vectors and lists
ELEMENTS OF A VECTOR
result.
> a <- c(1, 2, 5, 3, 6, -2, 4)
> a[3]
[1] 5
> a[c(1, 3, 5)]
[1] 1 5 6
> a[2:6]
[1] 2 5 3 6 -2
The colon operator used in the last statement is used to generate a sequence of
numbers. For example, a <- c(2:6) is equivalent to a <- c(2, 3, 4, 5, 6).
KEY PROPERTIES OF A VECTOR
(Atomic vectors and lists are the building blocks for other important vector types like factors
and dates. I call these augmented vectors, because they are vectors with additional attributes,
including class. Because augmented vectors have a class, they behave differently to the atomic
vector on which they are built. E. g.
•Dates
•Date-times)
TYPES OF VECTORS
There is only one difference between atomic vectors and lists. In an atomic vector,
all the elements are of the same type, but in the list, the elements are of different
data types.
FUNCTIONS FOR VECTORS
1.rep()
2.seq()
3.is.vector()
4.as.vector()
5.any()
6.all()
7.lapply()
8.sapply()
The rep() Function
The rep() function repeats a vector, or value, a given number of times. It then returns a vector
with the repeated values.
Each Lengh.out
The seq() Function
The all() function takes a vector and a logical condition as input arguments. It
checks the vector against the condition and creates a logical vector. It then
returns TRUE if all the elements in the logical vector are TRUE, and FALSE if all
elements are not TRUE.
The lapply() Function
The lapply() function takes a vector, list or a data frame and a function. The
lapply() function applies a function to all elements of a vector, list or data
frames. The function then returns the result in the form of a list
The sapply() Function
The sapply() is very similar to the lappy() function. The only difference is
that the sapply() function returns the result in the form of a vector.
Arithmetic Operators
Operat Description Example
or
+ Adds two vectors v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v+t) it produces the following result −
[1] 10.0 8.5 10.0