Sorting Vector:
Sort() function is used to sort elements of a vector
Examples:
Sorting a numeric vector
> x <- c( 20, 4, -7,6,60,0,-2)
> sort.output <- sort(x)
> sort.output
[1] -7 -2 0 4 6 20 60
Sorting above vector in reverse order
> revsort.output <- sort( x, decreasing = TRUE)
> print(revsort.output)
[1] 60 20 6 4 0 -2 -7
Sorting a character vector
> x <- c(“Amar”, “Akbar”, “Athony”)
> sort.output <- sort(x)
> print(sort.output)
[1] “Akbar” “Amar” “Athony”
Sort above in reverse order
> revsort.output <- sort( x, decreasing = TRUE)
> print(revsort.output)
[1] “Athony” “Amar” “Akbar”
Vector Index:
Vector Index displays a specific element of it.
> x <- c( 20, 4, -7,6,60,0,-2)
> x[4]
[1] 6
To print all element except the selected one from above vector
> x[-2]
[1] 20 -7 6 60 0 -2
Result of out – of range vector
> x[8]
[1] NA
Numeric Index Vector:
Numeric Index vector is used to slice some elements out of the vector in to a new vector
Example:
> slc <- c( 2, 4, 5, -11)
> slc[c(1,4)]
[1] 2 -11
Range Index Vector:
Range Index is used to list print a slice of element in certain range
> slc[c(2:4)]
[1] 4 5 -11
Logical Index Vector:
Logical Index Vector is used to slice elements from an existing vector of same length using its TRUE value.
> slc <- c( 2, 4, 5, -11)
> LOGIC <- c( TRUE, TRUE, TRUE, FALSE)
> slc[LOGIC]
[1] 2 4 5
Vector Arithmetic:
Same length vectors can be added, subtracted, multiplied, divided in an output
Example:
> x <- c( 2, 4, 5, -11)
> y <- c( 1, -8, 5, 30)
> add <- x+y
> print(add)
[1] 3 -4 10 19
> sub <- x-y
> print(sub)
[1] 1 12 0 -41
> mul <- x*y
> print(mul)
[1] 2 -32 25 -330
> div <- x/y
> print(div)
[1] 2.0000000 -0.5000000 1.0000000 -0.3666667