TANSCHE : SMPTS33 - Mathematical Statistics with R Programming - Unit 4

R Programming Unit 4 – Flow Control & Built-in Functions

📊 STATISTICS WITH R PROGRAMMING

Madurai Kamaraj University · II B.Sc. Mathematics, III Semester · TANSCHE Syllabus

ARO Study Circle

Chapter 4 · Flow Control in R

Syllabus: Decision making (using if statement – if-else statement – Nested If-Else statement – ifelse function – Switch statement) – Loops (for loop – while Loop – repeat Loop) – Function definition and Function Calling – Function without arguments – Built-in functions

4.1 Decision Making

Decision making structures are used by the programmer to specify one or more conditions to be evaluated or tested by the program. A statement or statements need to be executed if the condition is TRUE and optionally other statements to be executed if the condition is FALSE.

4.1.1 if Statement

An if statement consists of a boolean expression followed by one or more statements. If the boolean expression evaluates to TRUE, then the block of code inside the if statement will be executed. If boolean expression evaluates to FALSE, then the first set of code after the end of if statement (after the closing curly brace) will be executed.

Key Points:
• Boolean expression can be a logical or numeric vector, but only the first element is taken into consideration.
• In the case of numeric vector, zero is taken as FALSE, rest as TRUE.
if (boolean_expression) { # statement(s) will execute if the boolean expression is true } x <- 10 if (x > 0) { cat(x, "is a positive number\n") }
10 is a positive number

4.1.2 if...else Statement

An if statement can be followed by an optional else statement which executes when the boolean expression is FALSE.

if (boolean_expression) { # statement(s) will execute if boolean expression is true } else { # statement(s) will execute if boolean expression is false } x <- -5 if (x > 0) { cat(x, "is a positive number\n") } else { cat(x, "is a negative number\n") }
-5 is a negative number
# Single line if...else x <- 10 if (x > 0) cat(x, "is a positive number\n") else cat(x, "is a negative number\n")
10 is a positive number

4.1.3 Nested if...else Statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. We can nest as many if...else statements as we want. Only one statement will get executed depending upon the boolean expression.

if (boolean_expression_1) { # executes when boolean_expression_1 is true } else if (boolean_expression_2) { # executes when boolean_expression_2 is true } else if (boolean_expression_3) { # executes when boolean_expression_3 is true } else { # executes when none of the above conditions is true } x <- 19 if (x < 0) { cat(x, "is a negative number") } else if (x > 0) { cat(x, "is a positive number") } else { print("Zero") }
19 is a positive number

4.1.4 ifelse() Function

Most functions in R take vector as input and output a resultant vector. The ifelse() function is the vector equivalent form of the if...else statement.

ifelse(boolean_expression, x, y) a <- c(5, 7, 2, 9) ifelse(a %% 2 == 0, "even", "odd")
[1] "odd" "odd" "even" "odd"
Explanation: The boolean_expression is a %% 2 == 0 which results into the vector (FALSE, FALSE, TRUE, FALSE). The x vector ("even") gets recycled to ("even","even","even","even") and y vector ("odd") gets recycled to ("odd","odd","odd","odd"). Hence the result is evaluated accordingly.

4.1.5 switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

switch(expression, case1, case2, case3, ...) switch(2, "red", "green", "blue") switch("color", "color" = "red", "shape" = "square", "length" = 5)
[1] "green"
[1] "red"
Explanation: If the value evaluated is a number, that item of the list is returned. In the first example, "red", "green", "blue" form a three-item list, and 2 returns "green". The result of the statement can be a string as well. In the second example, "color" is the string that is matched and its value "red" is returned.

4.2 Loops

In general, statements are executed sequentially. Loops are used in programming to repeat a specific block of code. R provides various looping structures like for loop, while loop and repeat loop.

4.2.1 for Loop

A for loop is a repetition control structure that allows us to efficiently write a loop that needs to execute a specific number of times. A for loop is used to iterate over a vector in R programming.

for (value in sequence) { statements } # Count the number of even numbers from a vector x <- c(2, 5, 3, 9, 8, 11, 6) count <- 0 for (val in x) { if (val %% 2 == 0) count <- count + 1 } cat("No: of even numbers in", x, "is", count, "\n") # Iterating over character vector v <- c("a", "e", "i", "o", "u") for (vowel in v) print(vowel)
No: of even numbers in 2 5 3 9 8 11 6 is 3
[1] "a"
[1] "e"
[1] "i"
[1] "o"
[1] "u"

4.2.2 while Loop

In R programming, while loops are used to loop until a specific condition is met.

while (test_expression) { statement } # Sum of first 5 natural numbers num <- 5 sum_val <- 0 while (num > 0) { sum_val <- sum_val + num num <- num - 1 } cat("The sum is", sum_val, "\n")
The sum is 15

4.2.3 repeat Loop

A repeat loop is used to iterate over a block of code multiple number of times. There is no condition check in repeat loop to exit the loop. We must ourselves put a condition explicitly inside the body of the loop and use the break statement to exit the loop. Otherwise it will result in an infinite loop.

repeat { statements if (condition) { break } } # Prints numbers from 1 to 5 x <- 1 repeat { print(x) x <- x + 1 if (x > 5) { break } }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

4.3 Loop Control Statements

Loop control statements are also known as jump statements. They change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. The loop control statements in R are break statement and next statement.

4.3.1 break Statement

A break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. In a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

x <- 1:10 for (val in x) { if (val == 3) { break } print(val) }
[1] 1
[1] 2

4.3.2 next Statement

A next statement is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts the next iteration of the loop. This is equivalent to the continue statement in C, Java and Python.

x <- 1:10 for (val in x) { if (val == 3) { next } print(val) }
[1] 1
[1] 2
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
Quick Reference Card
ConstructDescription
if (condition) { ... }Executes block if condition is TRUE
if (condition) { ... } else { ... }Executes first block if TRUE, else second block
ifelse(vector_condition, x, y)Vectorized if-else
switch(expr, case1, case2, ...)Multi-way branching
for (var in sequence) { ... }Iterates over elements of a vector
while (condition) { ... }Repeats while condition is TRUE
repeat { ... if (condition) break }Infinite loop with explicit break
breakExits the current loop
nextSkips to the next iteration of the loop

4.4 Function Definition

Functions are used to logically break our code into simpler parts which become easy to maintain and understand. A function is a set of statements organized together to perform a specific task. R has a large number of built-in functions and the user can create their own functions. A function is an object, with or without arguments. The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects.

Components of a Function in R:
Function name – This is the actual name of the function. It is stored in R environment as an object with this name.
Arguments – When a function is invoked, we can pass values to the argument. Arguments are optional. A function may or may not contain arguments. The arguments can also have default values.
Function body – The function body contains a collection of statements that defines what the function does.
func_name <- function(argument) { statement }
Key Points:
• The reserved word function is used to declare a function in R.
• The statements within the curly braces form the body of the function.
• These braces are optional if the body contains only a single expression.
• The function object is given a name by assigning it to a variable.

4.5 Function Calling

We can create user-defined functions in R. They are specific to what a user wants and once created they can be used like built-in functions.

4.5.1 Function with Arguments

# Function to print x raised to the power y power <- function(x, y) { result <- x^y cat(x, "raised to the power", y, "is", result, "\n") } # Function Calling power(2, 3)
2 raised to the power 3 is 8
Note: The arguments used in the function declaration (x and y) are called formal arguments and those used while calling the function are called actual arguments.

4.5.2 Function without Arguments

# Function to print the square of numbers from 1 to 5 square <- function() { for (i in 1:5) cat("Square of", i, "is", (i*i), "\n") } # Function Calling square()
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

4.5.3 Function with Named Arguments

In positional argument matching, formal arguments to the actual arguments takes place in positional order. In the call power(8,2), the formal arguments x and y are assigned 8 and 2 respectively. We can also call the function using named arguments. When calling a function in this way, the order of the actual arguments doesn't matter.

power(2, 3) power(x = 2, y = 3) power(y = 3, x = 2)
2 raised to the power 3 is 8
2 raised to the power 3 is 8
2 raised to the power 3 is 8

Mixing Named and Unnamed Arguments

We can use named and unnamed arguments in a single function call. In such case, all the named arguments are matched first and then the remaining unnamed arguments are matched in a positional order.

power(x = 2, 3) power(2, y = 3)

4.5.4 Function with Default Arguments

We can assign default values to arguments in a function in R. This is done by providing an appropriate value to the formal argument in the function declaration. If no value is passed for that argument, then the default value is taken. If a value is passed, then the default value will be overridden.

# Function with default value for y power <- function(x, y = 2) { result <- x^y cat(x, "raised to the power", y, "is", result, "\n") } power(2) power(2, 3)
2 raised to the power 2 is 4
2 raised to the power 3 is 8

4.6 Built-in Functions

There are several built-in functions available in R. These functions can be directly used in user written programs. The built-in functions can be grouped into mathematical functions, character functions, statistical functions, date functions, time functions and other useful functions.

4.6.1 Mathematical Functions

1. abs()

This function computes the absolute value of numeric data. Syntax: abs(x), where x is any numeric value, array or vector.

abs(-1) abs(20) # Absolute value of vector x <- c(-2, 4, 0, 45, 9, -4) abs(x) # Matrix x x <- matrix(c(-3, 5, -7, 1, -9, 4), nrow = 3, ncol = 2, byrow = TRUE) x # Absolute value of first row abs(x[1,]) # Absolute value of first column abs(x[,1])
[1] 1
[1] 20
[1] 2 4 0 45 9 4
[,1] [,2]
[1,] -3 5
[2,] -7 1
[3,] -9 4
[1] 3 5
[1] 3 7 9

2. sin(), cos() and tan()

These functions compute sine, cosine and tangent values of numeric data in radians.

sin(10) cos(90) tan(50) x <- c(-2, 4, 0, 45, 9, -4) sin(x) cos(x) tan(x)
[1] -0.5440211
[1] -0.4480736
[1] -0.2719006
[1] -0.9092974 -0.7568025 0.0000000 0.8509035 0.4121185 0.7568025
[1] -0.4161468 -0.6536436 1.0000000 0.5253220 -0.9111303 -0.6536436
[1] 2.1850399 1.1578213 0.0000000 1.6197752 -0.4523157 -1.1578213

3. asin(), acos() and atan()

These functions compute the inverse sine, inverse cosine and inverse tangent values of numeric data in radians.

asin(1) acos(1) atan(50)
[1] 1.570796
[1] 0
[1] 1.550799

4. exp()

This function computes the exponential value of a number or number vector, ex.

exp(5) exp(c(1, 2, 3))
[1] 148.4132
[1] 2.718282 7.389056 20.085537

5. ceiling()

This function returns the smallest integer larger than the parameter.

ceiling(2.58) ceiling(c(3.5, 2.1, 6.9))
[1] 3
[1] 4 3 7

6. floor()

This function returns the largest integer not greater than the given number.

floor(2.58) floor(c(3.5, 2.1, 6.9))
[1] 2
[1] 3 2 6

7. round()

This function returns the integer rounded to the given number.

round(2.588) round(c(3.509, 2.672, 6.295), 2)
[1] 3
[1] 3.51 2.67 6.30

8. trunc()

This function returns the integer truncated with decimal part removed.

trunc(2.99) trunc(c(3.509899, 2.67231, 6.299982))
[1] 2
[1] 3 2 6

9. signif()

This function rounds the values in its first argument to the specified number of significant digits.

signif(2.5878888, 3) signif(c(3.509899, 2.67231, 6.299982), 2)
[1] 2.59
[1] 3.5 2.7 6.3

10. sqrt()

This function computes the square root of a numeric vector.

sqrt(25) sqrt(c(9, 64, 81))
[1] 5
[1] 3 8 9

11. log(), log10(), log2(), log(x, b)

  • log() computes natural logarithms
  • log10() computes common logarithms with base 10
  • log2() computes binary logarithms with base 2
  • log(x, b) computes logarithms with base b
log(5) log10(5) log2(5) log(5, base = 3) x <- c(10, 20, 30) log(x) log10(x) log2(x) log(x, base = 3)
[1] 1.609438
[1] 0.69897
[1] 2.321928
[1] 1.464974
[1] 2.302585 2.995732 3.401197
[1] 1.000000 1.301030 1.477121
[1] 3.321928 4.321928 4.906891
[1] 2.095903 2.726833 3.095903

12. max() and min()

max() computes the maximum value of a vector. min() computes the minimum value.

x <- c(10, 289, -100, 8000) max(x) min(x)
[1] 8000
[1] -100

13. beta() and lbeta()

beta() returns the beta value. lbeta() returns the natural logarithm of the beta function. Beta function: B(a, b) = Γ(a)Γ(b) / Γ(a+b)

beta(4, 9) lbeta(4, 9) x <- c(3, 6, 4) y <- c(7, 4, 12) beta(x, y)
[1] 0.0005050505
[1] -7.590852
[1] 0.0039682540 0.0019841270 0.0001831502

14. gamma()

This function returns the gamma function Γ(x).

gamma(5) gamma(c(1, 2, 3))
[1] 24
[1] 1 1 2

15. factorial()

This function computes factorial of a number or a numeric vector.

factorial(5) factorial(c(1, 2, 3, 4))
[1] 120
[1] 1 2 6 24

4.6.2 Character Functions

1. agrep()

This function searches for approximate matches to pattern within each element of the string.

x <- c("R language", "and", "SAND") agrep("an", x) agrep("an", x, ignore.case = TRUE) agrep("uag", x, ignore.case = TRUE) agrep("uag", x, ignore.case = TRUE, max = 1) agrep("uag", x, ignore.case = TRUE, max = 2)
[1] 1 2
[1] 1 2 3
[1] 1
[1] 1
[1] 1 2 3

2. char.expand()

This function seeks a unique match of its first argument among the elements of its second.

x <- c("sand", "and", "land") char.expand("an", x, warning("no expand")) char.expand("a", x, warning("no expand")) char.expand("xx", x, warning("no expand"))
[1] "and"
[1] "and"
[1] NA
Warning message: In eval(nomatch) : no expand

3. charmatch()

This function finds matches between two arguments and returns the index position.

charmatch("an", c("and", "sand")) charmatch("an", c("end", "and", "sand")) charmatch("an", "sand")
[1] 1
[1] 2
[1] NA

4. charToRaw()

This function converts character to ASCII or "raw" objects.

charToRaw("a")
[1] 61

5. chartr()

This function is used for character substitutions.

x <- "apples are red" chartr("a", "g", x)
[1] "gapples gre red"

6. dQuote()

This function is used for putting double quote on a text.

dQuote("2013-06-12 19:18:05")
[1] "2013-06-12 19:18:05"

7. format()

Numbers and strings can be formatted to a specific style using format() function.

result <- format(23.123456789, digits = 9) print(result) # Display numbers in scientific notation result <- format(c(6, 13.14521), scientific = TRUE) print(result) # Minimum number of digits to the right of the decimal point result <- format(23.47, nsmall = 5) print(result) # Format treats everything as a string result <- format(6) print(result) # Numbers are padded with blank in the beginning for width result <- format(13.7, width = 6) print(result) # Left justify strings result <- format("Hello", width = 8, justify = "l") print(result) # Justify string with center result <- format("Hello", width = 8, justify = "c") print(result)
[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] " 13.7"
[1] "Hello "
[1] " Hello "

8. gsub()

This function replaces all matches of a string.

gsub("are", "were", "apples are red")
[1] "apples were red"

9. nchar() and nzchar()

nchar() determines the size of each element of a character vector. nzchar() tests whether elements are non-empty strings.

x <- c("red", "green", "blue", "") nchar(x) nzchar(x)
[1] 3 5 4 0
[1] TRUE TRUE TRUE FALSE

10. noquote()

This function prints out strings without quotes.

letters noquote(letters)

11. paste()

Strings in R are combined using the paste() function.

a <- "Hello," b <- 'Good Morning' c <- "Everyone!" print(paste(a, b, c)) print(paste(a, b, c, sep = "-")) print(paste(a, b, c, sep = "-", collapse = ""))
[1] "Hello, Good Morning Everyone!"
[1] "Hello,-Good-Morning-Everyone!"
[1] "Hello,-Good-Morning-Everyone!"

12. replace()

This function replaces the values in x with indices given in list by those given in values.

x <- c("green", "red", "yellow") replace(x, 1, "black") replace(x, c(1, 2), c("blue", "white"))
[1] "black" "red" "yellow"
[1] "blue" "white" "yellow"

13. sQuote()

This function is used for putting single quote on a text.

sQuote("2013-06-12 19:18:05")
[1] "2013-06-12 19:18:05"

14. strsplit()

This function splits the elements of a character vector into substrings.

strsplit("apples are red cherries are red", " ")
[1] "apples" "are" "red" "cherries" "are" "red"

15. substr()

This function extracts or replaces substrings in a character vector.

substr("programming", 2, 3) x <- c("red", "blue", "green", "yellow") substr(x, 2, 3) substr(x, 2, 3) <- "gh" x
[1] "ro"
[1] "ed" "lu" "re" "el"
[1] "rgh" "bghe" "gghen" "yghlow"

16. tolower()

This function converts string to its lower case.

tolower("R PROGRAMMING") tolower(c("GREEN", "Red", "Black"))
[1] "r programming"
[1] "green" "red" "black"

17. toString()

This function produces a single character string describing an R object.

toString(c("Green", "Red", "Black")) toString(c("Green", "Red", "Black"), width = 5) toString(c("Green", "Red", "Black"), width = 12)
[1] "Green, Red, Black"
[1] "Gr..."
[1] "Green, R..."

18. toupper()

This function converts string to its upper case.

toupper("r programming") toupper(c("GREEN", "Red", "Black"))
[1] "R PROGRAMMING"
[1] "GREEN" "RED" "BLACK"

4.6.3 Statistical Functions

1. mean()

Calculates the average or mean. Syntax: mean(x, trim = 0, na.rm = FALSE)

x <- c(10, 2, 30, 4, 5, 6, 70, 8, 9, 10) y <- c(1, 2, 3, 4, 5, NA) mean(x) mean(x, trim = 0.2) mean(y, na.rm = TRUE)
[1] 15.4
[1] 8
[1] 3

2. median()

Calculates the median (middle value). Syntax: median(x, na.rm = FALSE)

x <- c(10, 2, 30, 2, 5, 8, 70, 8, 9, 2) y <- c(3, 2, 3, 4, 5, NA) median(x) median(y, na.rm = TRUE)
[1] 8
[1] 3

3. var()

Returns the estimated variance. Syntax: var(x, na.rm = FALSE)

var(x) var(y, na.rm = TRUE)
[1] 446.0444
[1] 1.3

4. sd()

Returns the estimated standard deviation. Syntax: sd(x, na.rm = FALSE)

sd(x) sd(y, na.rm = TRUE)
[1] 21.11976
[1] 1.140175

5. scale()

Returns the standard scores (z-scores). Syntax: scale(x, center = TRUE, scale = TRUE)

x <- matrix(1:9, 3, 3) scale(x)
[,1] [,2] [,3]
[1,] -1 -1 -1
[2,] 0 0 0
[3,] 1 1 1
attr(,"scaled:center") [1] 2 5 8
attr(,"scaled:scale") [1] 1 1 1

6. sum()

Adds up all elements of a vector.

sum(1:10) sum(c(1, 2, 3, 4, 5))
[1] 55
[1] 15

7. diff()

Returns suitably lagged and iterated differences. Syntax: diff(x, lag = 1, differences = 1)

diff(c(5, 20, 14, 4, 2, 10, 19)) diff(c(5, 20, 14, 4, 2, 10, 19), lag = 2) diff(c(5, 20, 14, 4, 2, 10, 19), differences = 2)
[1] 15 -6 -10 -2 8 9
[1] 9 -16 -12 6 17
[1] -21 -4 8 10 1

8. range()

Returns a vector of the minimum and maximum values.

range(x) range(y, na.rm = FALSE)
[1] 2 70
[1] NA NA

9. quantile()

A quantile (percentile) tells how much of data lies below a certain value.

quantile(1:10, c(0.03, 0.5))
3% 50%
1.27 5.50

10. rank()

Returns the ranks of the numbers in vector x.

x <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) rank(x) rank(x, ties.method = "average") rank(x, ties.method = "first") rank(x, ties.method = "last") rank(x, ties.method = "max") rank(x, ties.method = "min")
[1] 4.5 1.5 6.0 1.5 8.0 11.0 3.0 10.0 8.0 4.5 8.0
[1] 4 1 6 2 7 11 3 10 8 5 9
[1] 5 2 6 1 9 11 3 10 8 4 7
[1] 5 2 6 1 9 11 3 10 8 4 7
[1] 5 2 6 2 9 11 3 10 9 5 9

11. moment()

Calculates central moments. Requires e1071 package.

library(e1071) x <- c(24, 30, 27, 24, 39, 45, 42, 51) moment(x, order = 3, center = TRUE)
[1] 205.0312

12. skewness()

Measures asymmetry in a statistical distribution. Requires e1071 package.

library(e1071) skewness(x)
[1] 0.1843205

13. kurtosis()

Measures the "tailedness" of the probability distribution. Requires e1071 package.

library(e1071) kurtosis(x)
[1] -1.804028

4.6.4 Date and Time Functions

1. Date Class

R provides three date/time classes: Date, POSIXct and POSIXlt.

date() Sys.Date() Sys.time() # Creating dates dt1 <- as.Date("2012-07-22") dt1 dt2 <- as.Date("04/20/2011", format = "%m/%d/%Y") dt2 dt3 <- as.Date("October 6, 2010", format = "%B %d, %Y") dt3
[1] "Wed Sep 06 09:57:55 2017"
[1] "2017-09-06"
[1] "2017-09-06 10:01:00 IST"
[1] "2012-07-22"
[1] "2011-04-20"
[1] "2010-10-06"
Calculations with Dates
# Difference between two dates dt1 - dt2 difftime(dt1, dt2, units = "weeks") # Add or subtract days dt2 + 10 dt2 - 10 # Vector of dates three.dates <- as.Date(c("2010-07-22", "2011-04-20", "2012-10-06")) three.dates diff(three.dates) # Sequence of dates seq(dt1, length = 6, by = "week") seq(dt1, length = 6, by = 14) seq(dt1, length = 6, by = "2 weeks")

2. POSIXct Class

Used for times in data. "ct" stands for calendar time.

tm1 <- as.POSIXct("2013-07-24 23:55:26") tm1 tm2 <- as.POSIXct("25072013 08:32:07", format = "%d%m%Y %H:%M:%S") tm2 # Specify time zone tm3 <- as.POSIXct("2010-12-01 11:42:03", tz = "GMT") tm3 # Compare times tm2 > tm1 # Add or subtract seconds tm1 + 30 tm1 - 30 # Difference between times tm2 - tm1
[1] "2013-07-24 23:55:26 PDT"
[1] "2013-07-25 08:32:07 PDT"
[1] "2010-12-01 11:42:03 GMT"
[1] TRUE
[1] "2013-07-24 23:55:56 PDT"
[1] "2013-07-24 23:54:56 PDT"
Time difference of 8.611 hours

3. POSIXlt Class

"lt" stands for local time. POSIXlt objects are lists enabling easy extraction of specific components.

tm1.lt <- as.POSIXlt("2013-07-24 23:55:26") tm1.lt # Extract components unlist(tm1.lt) # Extract specific component tm1.lt$sec tm1.lt$day # Truncate or round off time trunc(tm1.lt, "days") trunc(tm1.lt, "mins")

4.6.5 Other Useful Functions

1. seq()

Generates a sequence.

seq(1, 15, 2)
[1] 1 3 5 7 9 11 13 15

2. rep()

Repeats x n times.

rep(1:3, 4)
[1] 1 2 3 1 2 3 1 2 3 1 2 3

3. cut()

Divides continuous variable into factor with n levels.

x <- c(1, 2, 3, 1, 2, 3, 1) cut(x, 2) cut(rep(1, 5), 4)

4. which()

Gives the TRUE indices of a logical object.

x <- matrix(1:9, 3, 3) which(x %% 2 == 0, arr.ind = TRUE) which(x %% 2 == 0, arr.ind = FALSE)
row col
[1,] 2 1
[2,] 1 2
[3,] 3 2
[1] 2 4 6 8

5. table()

Builds a contingency table of counts.

# Using built-in dataset mtcars table(mtcars$am) table(mtcars$mpg > 15)
0 1
19 13
FALSE TRUE
6 26
Quick Reference Card
Function CategoryExamples
Mathematicalabs(), sqrt(), log(), exp(), ceiling(), floor(), round(), sin(), cos(), tan()
Characterpaste(), substr(), tolower(), toupper(), gsub(), strsplit(), nchar()
Statisticalmean(), median(), sd(), var(), sum(), range(), quantile(), rank()
Date/TimeSys.Date(), Sys.time(), as.Date(), as.POSIXct(), as.POSIXlt()
Otherseq(), rep(), cut(), which(), table()

📘 R Programming · Unit 4 · Flow Control & Built-in Functions

Prepared by ARO Study Circle

Post a Comment

0 Comments