R PROGRAMMING Flashcards
Sorting
The function sort, sorts
a vector in increasing order.
Order
It takes vectors as input, and returns the vector of indexes that sorts the input vector.
example for order
ind <- order(murders$total)
# This gives the index of total murder in increasing order
murders$abb[ind]
Example For order
x <- c(5,4,6,3,1,0)
index <- order(x)
x[index]
output
ans: 0 1 3 4 5 6
MAX
If we are only interested in the value, we can use max function
Which.Max
If we want the index, we use which.max function
RANK
For any given vector it returns a vector with the rank of the first
entry, second entry, etc., of the input vecto
Which.max example
i_max <- which.max(murders$total)
murders$state[i_max]
#> [1] “California”
HOW TO REORDER USING ORDER FUNCTION
STEP 1 : FIND THE INDEX AT WHICH THE VECTORS ARE SORTED.
STEP 2: REORDER THE OBJECT USING ASSIGNED OBJECT INSIDE THE SQUARE BRACKET []
TAKE input from the user
When we are working with R in an interactive session, we can use readline() function to take input from the user (terminal)
TAKE input from the user EXAMPLE
my.name <- readline(prompt=”Enter name: “)
my.age <- readline(prompt=”Enter age: “)
# convert character into integer
my.age <- as.integer(my.age)
print(paste(“Hi,”, my.name, “next year you will be”, my.age+1, “years old.”))