r programming 2nd unit
r programming 2nd unit
8-
1
STATISTICAL COMPUTING AND R PROGRAMMING
2) Delimiter: The delimiter is a character used to separate entries in each line.
3) Missing Value: A unique character string denoting missing values
This is converted to `NA` when reading.
• Table-format files typically have extensions like `.txt` or `.csv`.
8-
2
STATISTICAL COMPUTING AND R PROGRAMMING
• read.table() can be used for reading tabular data from web-based files.
• We can import data directly from the internet.
• Example: To read tabular data from a web-based file located at the following URL:
https://example.com/data.txt.
# Specify the URL of the web-based file url <- "https://example.com/data.txt"
# Use read.table to read the data from the web-based file my_data <- read.table(url, header = FALSE,
sep = "\t")
8-
3
STATISTICAL COMPUTING AND R PROGRAMMING
print(my_data)
Output:
Name Age City
Krishna 26 Mysore
Arjuna 31 Mandya
Karna 29 Maddur
Explanation of above program:
• file_path is set to the location of the data.csv file.
• We use read.csv to read the data from the CSV file into the my_data data frame.
• Since the CSV file has a header row with column names, we don't need to specify the header
argument explicitly; it defaults to TRUE.
• The default sep argument is ",", which is suitable for CSV files.
8-
4
STATISTICAL COMPUTING AND R PROGRAMMING
# Confirmation message
cat(paste("Data saved to", file_name))
Explanation of above program:
• We have a sample data frame called my_data with columns "Name," "Age," and "Score."
• We specify the file_name as "my_data.txt" to define the name of the output file.
• We use the write.table function to write the data frame to the specified file.
• We set sep to "\t" to indicate that the values should be tab-separated.
• We use row.names = FALSE to exclude row names from the output.
• We set col.names = TRUE to include column names in the output.
• We set quote = TRUE to enclose character and factor fields in quotes for proper formatting.
8.3.2 Plots and Graphics Files
8.3.2.1 Using `jpeg` Function
• jpeg() is used to create and save plots as JPEG image files.
• You can specify parameters like the filename, width, height, and quality of the JPEG image.
• Syntax: jpeg(filename, width, height)
where
file: The name of the JPEG image file to which the graphics will be written
width and height: The width and height of the JPEG image in pixels.
• Example:
# Create sample data
x <- c(1, 2, 3, 4, 5)
y <- c(1, 4, 9, 16, 25)
# Open a JPEG graphics device and save the plot to a file jpeg(filename =
"scatter_plot.jpg", width = 800, height = 600) # Replot the same graph (this
time it will be saved as a JPEG) plot(x, y, type = "p", main = "Scatter Plot
Example") dev.off() # Close the JPEG graphics device
Explanation of above program:
• We create a simple scatter plot of x and y data points.
• We use the jpeg() function to specify the output as a JPEG image with the filename
"scatter_plot.jpg."
• We set the dimensions of the output image using the width and height parameters (800x600 pixels).
• The quality parameter is set to 90, which controls the image compression quality (higher values
result in better quality but larger file sizes).
• After opening the graphics device, we replot the same graph, which is now directed to the JPEG
file.
8-
5
STATISTICAL COMPUTING AND R PROGRAMMING
• Finally, we close the JPEG graphics device using dev.off().
8-
6
STATISTICAL COMPUTING AND R PROGRAMMING
# Use dput to serialize the list and save it to a text file dput(my_list, file =
8-
7
STATISTICAL COMPUTING AND R PROGRAMMING
"my_list.txt")
# Use dget to read and recreate the R object from the text file recreated_list <- dget(file =
"my_list.txt")
8-
8
STATISTICAL COMPUTING AND R PROGRAMMING
9.1 Scoping
• Scoping-rules determine how the language accesses objects within a session.
• These rules also dictate when duplicate object-names can coexist.
9.1.1 Environments
• Environments are like separate compartments where data structures and functions are stored.
• They help distinguish identical names associated with different scopes.
• Environments are dynamic and can be created, manipulated, or removed.
• Three important types of environments are:
1) Global Environment
2) Package Environments and Namespaces
3) Local Environments
CALLING FUNCTIONS
9•
1
STATISTICAL COMPUTING AND R PROGRAMMING
• Namespaces define the visibility of package functions.
• Use: Package environments and namespaces allow you to use functions from different packages
without conflicts.
• Syntax to list items in a package environment:
`ls("package:package_name")`.
• Example:
R> ls("package:graphics") #lists objects contained in graphics package environment "abline"
"arrows" "assocplot" "axis"
9.1.2 Search-path
• A search-path is used to access data structures and functions from different environments.
• The search-path is a list of environments available in the session.
• search() is used to view the search-path.
• Example:
R> search()
".GlobalEnv" "package:stats" "package:graphics" “package:base”
• The search-path
starts at the global environment (.GlobalEnv) and
ends with the base package environment (package:base).
• When looking for an object, R searches environments in the specified order.
• If the object isn't found in one environment, R proceeds to the next in the searchpath.
• environment() can be used to determine function's environment.
R> environment(seq)
<environment: namespace:base>
R> environment(arrows)
<environment: namespace:graphics>
CALLING FUNCTIONS
9•
2
STATISTICAL COMPUTING AND R PROGRAMMING
• Argument matching refers to the process by which function-arguments are matched to their
corresponding parameter-names within a function call
• Five ways to match function arguments are
1) Exact matching
2) Partial matching
3) Positional matching
4) Mixed matching
5) Ellipsis (...) argument
9.2.1 Exact
• Exact matching is the default argument matching method.
• In this, arguments are matched based on their exact parameter-names.
• Advantages:
1) Less prone to mis-specification of arguments.
2) The order of arguments doesn't matter.
• Disadvantages:
1) Can be cumbersome for simple operations.
2) Requires users to remember or look up full, case-sensitive tags.
• Example:
R> mat <- matrix(data=1:4, nrow=2, ncol=2, dimnames=list(c("A","B"), c("C","D"))) R> mat
CD
A13
B 24
CALLING FUNCTIONS
9•
3
STATISTICAL COMPUTING AND R PROGRAMMING
• Arguments are matched to parameters based on their position.
• args() can be used to find the order of arguments in the function.
• Example:
R> args(matrix)
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) NULL
R> mat <- matrix(1:4, 2, 2, F, list(c("A","B"), c("C","D")))
R> mat
CD
A13
B 24
• Advantages:
1) Results in shorter, cleaner code for routine tasks.
2) No need to remember specific argument tags.
• Disadvantages:
1) Requires users to know and match the defined order of arguments.
2) Reading code from others can be challenging, especially for unfamiliar functions.
9.2.4 Mixed Matching
• Mixed matching allows a combination of exact, partial, and positional matching in a single function
call.
• Example:
R> mat <- matrix(1:4, 2, 2, dim=list(c("A","B"),c("C","D")))
R> mat
CD
A13
B 24
# Function call
fun(5, 1L, 6i, TRUE, "GeeksForGeeks", "Dots operator")
.
CALLING FUNCTIONS
9•
4
STATISTICAL COMPUTING AND R PROGRAMMING
10.1.1 if Statement
• This is basically a “one-way” decision statement.
• This is used when we have only one alternative.
• Syntax:
if(expression)
{
statement1;
}
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement1 is skipped.
• Example: Program to illustrate usage of if statement
n <- 7
# Check if n is positive or negative and print the result if (n > 0) {
cat("Number is a positive number\n")
}
if (n < 0) { cat("Number is a negative number\
n") }
Output:
Number is positive number
10-1
STATISTICAL COMPUTING AND R PROGRAMMING
10-2
STATISTICAL COMPUTING AND R PROGRAMMING
10-3
STATISTICAL COMPUTING AND R PROGRAMMING
if(expr3)
statement3 else
statement4
}
• Here, firstly expr1 is evaluated to true or false.
If the expr1 is evaluated to true, then expr2 is evaluated to true or false.
If the expr2 is evaluated to true, then statement1 is executed.
If the expr2 is evaluated to false, then statement2 is executed.
If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
If the expr3 is evaluated to true, then statement3 is executed.
If the expr3 is evaluated to false, then statement4 is executed
• Example: Program to illustrate usage of Nesting `if` Statements
a <- 7 b <- 8 c <- 6 if (a > b)
{ if (a > c) { cat("largest = ",
a, "\n")
} else {
cat("largest =", c, "\n")
}
} else { if (b > c)
{ cat("largest =", b, "\n")
} else {
cat("largest =", c, "\n")
}
}
Output:
Largest Value is: 8
10.1.5 else if Ladder Statement (Stacking `if` Statements) • This is basically a
“multi-way” decision statement.
• This is used when we must choose among many alternatives.
• Syntax:
if(expression1)
statement1;
else if(expression2)
statement2;
else if(expression3)
statement3
else if(expression4)
statement4 else
default statement5
• The expressions are evaluated in order (i.e. top to bottom). • If an expression is evaluated to true, then
→ statement associated with the expression is executed &
→ control comes out of the entire else if ladder
10-4
STATISTICAL COMPUTING AND R PROGRAMMING
• For ex, if exprression1 is evaluated to true, then statement1 is executed.
If all the expressions are evaluated to false, the last statement4 (default case) is executed.
• Example: Program to illustrate usage of Stacking `if` Statements
n <- 7
# Check if n is positive, negative, zero, or invalid and print the result if (n > 0)
{ cat("Number is Positive")
} else if (n < 0) {
cat("Number is Negative") } else
if (n == 0) { cat("Number is
Zero")
} else {
cat("Invalid input")
}
Output:
Number is Positive
10-5
STATISTICAL COMPUTING AND R PROGRAMMING
)
Output:
Well done
10-6
STATISTICAL COMPUTING AND R PROGRAMMING
2) Using integer indexes to access elements in vector.
• Example:
numbers <- c(1, 2, 3, 4, 5) for (i in
1: length(numbers)){
print(2 * numbers [i])
}
Output:
2 4 6 8 10
10.2.1.2 Nesting for Loops
• Nesting for loops involves placing one for loop inside another.
• This allows you to create complex iteration patterns where you iterate over elements of multiple data
structures.
for (i in 1:3) { for (j in
1:3) { product <- i * j
cat(product, "\t")
}
cat("\n")
}
Output:
1 2 3
2 4 6
3 6 9
Explanation of above program:
• The outer loop iterates through i from 1 to 3.
• For each value of i, the inner loop iterates through j from 1 to 3.
• Within the inner loop, it calculates the product of i and j, which is i * j, and prints it to the console
followed by a tab character ("\t").
• After each row of products is printed (after the inner loop), a newline character ("\n") is printed to
move to the next row.
10-7
STATISTICAL COMPUTING AND R PROGRAMMING
• If the expression is evaluated to false, the control comes out of the loop without executing the body of
the loop.
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is executed.
• After executing the body of the loop, control goes back to the beginning of the while statement.
• Example: Program to illustrate usage of while Loop
i <- 1 # Initialize a variable while (i <=
3) { cat("Welcome to R \n")
i <- i + 1
}
Output:
Welcome to R
Welcome to R
Welcome to R
row <- 1
identity_matrix <- matrix(0, nrow = n, ncol = n)
10-8
STATISTICAL COMPUTING AND R PROGRAMMING
• The apply function is used for applying a function to subsets of a data structure, such as rows or
columns of a matrix.
• It allows you to avoid writing explicit loops and can simplify your code.
• Syntax:
apply(X, MARGIN, FUN)
where
X: The data structure (matrix, data-frame, or array) to apply the function to. MARGIN: Specifies
whether the function should be applied to rows (1) or columns (2) of the data structure.
FUN: The function to apply to each subset.
• Example: Program to illustrate usage of apply function
# Create a sample matrix of exam scores
scores_matrix <- matrix(c(60, 70, 80, 90, 60, 70, 80, 90, 60, 70, 80, 90), nrow = 4 )
# Use apply to calculate the mean score for each student (across exams) mean_scores <-
apply(scores_matrix, 1, mean)
lapply() function
The lapply() function helps us in applying functions on list objects and returns a list object of the same
length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives
output in the form of a list object. Since the lapply() function applies a certain operation to all the
elements of the list it doesn’t need a MARGIN.
Syntax: lapply( x, fun )
Parameters:
● x: determines the input vector or an object.
● fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the lapply() function to a vector.
10-9
STATISTICAL COMPUTING AND R PROGRAMMING
"sudhanshu","devraj")
names
lapply(names, toupper)
Output:
sapply() function
The sapply() function helps us in applying functions on a list, vector, or data frame and returns an array
or matrix object of the same length. The sapply() function in the R Language takes a list, vector, or data
frame as input and gives output in the form of an array or matrix object. Since the sapply() function
applies a certain operation to all the elements of the object it doesn’t need a MARGIN. It is the same as
lapply() with the only difference being the type of return object.
Syntax: sapply( x, fun )
Parameters:
● x: determines the input vector or an object.
● fun: determines the function that is to be applied to input data.
Example:
10-10
STATISTICAL COMPUTING AND R PROGRAMMING
Here, is a basic example showcasing the use of the sapply() function to a vector.
y=c(3,2,4,2,34,5))
sample_data
sapply(sample_data, max)
Output:
10-11
STATISTICAL COMPUTING AND R PROGRAMMING
tapply() function
The tapply() helps us to compute statistical measures (mean, median, min, max, etc..) or a self-written
function operation for each factor variable in a vector. It helps us to create a subset of a vector and then
apply some functions to each of the subsets. For example, in an organization, if we have data of salary of
employees and we want to find the mean salary for male and female, then we can use tapply() function
with male and female as factor variable gender.
Syntax: tapply( x, index, fun )
Parameters:
● x: determines the input vector or an object.
● index: determines the factor vector that helps us distinguish the data.
● fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the tapply() function on the diamonds dataset which is
provided by the tidyverse package library.
Output:
10-12
STATISTICAL COMPUTING AND R PROGRAMMING
print(i)
}
Output
[1] 1
10-13
STATISTICAL COMPUTING AND R PROGRAMMING
[1] 2
[1] 3
Here, we have defined a vector of numbers from 1 to 7. Inside the for loop, we check if the current
number is 4 using an if statement.
If yes, then the break statement is executed and no further iterations are carried out. Hence, only numbers
from 1 to 3 are printed.
R next Statement
In R, the next statement skips the current iteration of the loop and starts the loop from the next iteration.
The syntax of the next statement is:
if (test_condition) {
next
}
If the program encounters the next statement, any further execution of code from the current iteration is
skipped, and the next iteration begins.
Let's check out a program to print only even numbers from a vector of numbers.
print(i)
}
Output
[1] 2
[1] 4
[1] 6
[1] 8
Here, we have used an if statement to check whether the current number in the loop is odd or not.
If yes, the next statement inside the if block is executed, and the current iteration is skipped.
We use the R repeat loop to execute a code block multiple times. However, the repeat loop doesn't have
any condition to terminate the lYou can use the repeat loop in R to execute a block of code multiple
10-14
STATISTICAL COMPUTING AND R PROGRAMMING
times. However, the repeat loop does not have any condition to terminate the loop. You need to put an
exit condition implicitly with a break statement inside the loop.
The syntax of repeat loop is:
repeat {
# statements
if(stop_condition) {
break
}
}
Here, we have used the repeat keyword to create a repeat loop. It is different from the for and while loop
because it does not use a predefined condition to exit from the loop.
Example 1: R repeat Loop
Let's see an example that will print numbers using a repeat loop and will execute until
the break statement is executed.
x=1
# Repeat loop
repeat {
print(x)
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
10-15
STATISTICAL COMPUTING AND R PROGRAMMING
[1] 5
Here, we have used a repeat loop to print numbers from 1 to 5. We have used an if statement to provide a
breaking condition which breaks the loop if the value of x is greater than 4.
10-16
STATISTICAL COMPUTING AND R PROGRAMMING
CHAPTER 11: WRITING FUNCTIONS
Functions
11•1
STATISTICAL COMPUTING AND R PROGRAMMING
fibo1 <- function() { fib_a <- 1 fib_b <-
1 cat(fib_a, ", ", fib_b, ", ", sep = "")
while (fib_b <= 150) { temp <-
fib_a + fib_b
fib_a <- fib_b fib_b <- temp
if (fib_b <= 150) { cat(fib_b,
", ", sep = "")
}
}
}
11•2
STATISTICAL COMPUTING AND R PROGRAMMING
# Call the function with a threshold value (e.g., 50) & assign the result to a variable
fibonacci_sequence <- fibo3(50)
Functions
11•3
STATISTICAL COMPUTING AND R PROGRAMMING
add_numbers <- function(x, y) {
result <- x + y return(result)
}
# Call the function and store the result in a variable sum_result <-
add_numbers(5, 3)
11.2 Arguments
11.2.1 Lazy Evaluation
• Lazy evaluation means expressions are evaluated only when needed.
• The evaluation of function-arguments is deferred until they are actually needed.
• The arguments are not evaluated immediately when a function is called but are evaluated when they
are accessed within the function.
• This can help optimize performance and save computational resources.
• Example:
lazy_example <- function(a, b)
{
cat("Inside the function\n") cat("a =", a, "\n") cat("b =", b, "\n") cat("Performing some
operations...\n") result <- a + b cat("Operations completed\n")
return(result)
}
# Create two variables x <- 10 y <- 20
# Call the function with the variables lazy_example(x, y)
Output:
Inside the function a = 10 b = 20
Performing some operations...
Operations completed
[1] 30
Explanation of above program:
• When we call lazy_example(x, y), we are passing the variables x and y as arguments to the function.
• Initially, the function prints "Inside the function" and then proceeds to print "a = 10" and "b = 20".
This indicates that the values of a and b are evaluated at this point.
• Next, the function prints "Performing some operations..." and calculates result as a + b.
11•4
STATISTICAL COMPUTING AND R PROGRAMMING
• However, it does not evaluate the actual values of x and y (i.e., 10 and 20) immediately. Instead, it
holds off on the computation until the result is needed.
• Finally, the function prints "Operations completed" and returns the result, which is 30
# Call the function without specifying width and height default_area <-
calculate_rectangle_area()
Functions
11•5
STATISTICAL COMPUTING AND R PROGRAMMING
• When we call `calculate_rectangle_area(width = 5, height = 4)` with custom values, the function
uses these values and returns the calculated area of 20, which is stored in the variable
`custom_area`.
11•6
STATISTICAL COMPUTING AND R PROGRAMMING
while (fibseq[counter] <= thresh) { fibseq <- c(fibseq,
fibseq[counter - 1] + fibseq[counter]) counter <- counter + 1
Figure 11-1: The default plot produced by a call to myfibplot, with thresh=150
11.3 Specialized Functions
11.3.1 Helper Functions
Functions
11•7
STATISTICAL COMPUTING AND R PROGRAMMING
• These functions are designed to assist another function in performing computations • They enhance
the readability of complex functions.
• They can be either defined internally or externally.
11.3.1.1 Externally Defined Helper Functions
• These functions are defined in external libraries or modules.
• They can be used in your code w/o defining them within your program.
• They are typically provided by programming language or third-party libraries
• They provide commonly used functionalities.
• Example: Externally defined helper function ‘mean’ is used to find mean of 5 nos.
values <- c(10, 20, 30, 40, 50) average <-
mean(values)
cat("The average is:", average, "\n")
Output:
The average is: 30
Explanation of above program:
• We use the `mean` function, which is an externally defined helper function provided by the R
programming language.
• mean() calculates the average of the numeric values in the `values` vector.
• We store the result in the `average` variable and then print it.
11•8
STATISTICAL COMPUTING AND R PROGRAMMING
• They are often employed to perform a single, temporary operation.
• They are discarded after use.
• Example: A disposable function to calculate the area of a rectangle once
calculate_rectangle_area <- function(length, width) { area <-
length * width cat("The area of the rectangle is:", area, "\n") }
# Use the disposable function to calculate the area of a specific rectangle calculate_rectangle_area(5,
3)
Output:
The area of the rectangle is: 15
Explanation of above program:
• We define a function called `calculate_rectangle_area` that calculates the area of a rectangle based
on its length and width.
• We use this function once to calculate the area of a specific rectangle with a length of 5 units and a
width of 3 units. Advantages of Disposable Functions • Convenient for simple, one-off tasks.
• Avoids cluttering the global environment with unnecessary function objects.
• Provides a concise way to define and use functions inline.
Functions
11•9
STATISTICAL COMPUTING AND R PROGRAMMING
• In the recursive case, for n greater than 2, we calculate the nth Fibonacci number by adding the (n-
1)th and (n-2)nd Fibonacci numbers. We do this by calling the myfibrec function recursively with n
- 1 and n - 2 as arguments.
• Finally, we call the f myfibrec function with n = 5 and print the result.
Figure 11-3: A visualization of the recursive calls made to myfibrec with n=5
11•10
STATISTICAL COMPUTING AND R PROGRAMMING
after the top-level function completes its execution. If the value is 1 (one) then it is printed as soon
as it has been encountered while if the value is 2 (two) then immediately the generated warning is
converted into an error.
● tryCatch(…): It helps to evaluate the code and assign the exceptions.
Condition Handling in R
Generally, if we encounter any unexpected errors while executing a program we need an efficient and
interactive way to debug the error and know what went wrong. However, some errors are expected but
sometimes the models fail to fit and throw an error. There are basically three methods to handle such
conditions and errors in R :
● try(): it helps us to continue with the execution of the program even when an error occurs.
● tryCatch(): it helps to handle the conditions and control what happens based on the conditions.
try-catch-finally in R
Unlike other programming languages such as Java, C++, and so on, the try-catch-finally statements
are used as a function in R. The main two conditions to be handled in tryCatch() are “errors” and
“warnings”.
Syntax:
check = tryCatch({
expression
}, warning = function(w){
code that handles the warnings
}, error = function(e){
code that handles the errors
}, finally = function(f){
clean-up code
})
Example:
# Applying tryCatch
tryCatch(
Functions
11•11
STATISTICAL COMPUTING AND R PROGRAMMING
# Specifying expression
expr = {
1+1
},
error = function(e){
},
warning = function(w){
},
finally = {
print("finally Executed")
Output:
[1] "Everything was fine."
[1] "finally Executed"
Suppress Warnings
● SuppressWarnings() function: A function in R used to temporarily suppress warnings in R code.
11•12
STATISTICAL COMPUTING AND R PROGRAMMING
● suppressWarnings({
● # Code that generates warning messages
● })
If you run this code, R will pause for three seconds before you can con- tinue using the console.
Sleeping will be used in this section as a surrogate for the delay caused by computationally
expensive operations, which is where progress bars are most useful.
To use Sys.sleep in a more common fashion, consider the following:
R> sleep_test(8)
[1] 8
Now, say you want to track the progress of this type of function as it exe- cutes. You can implement
a textual progress bar with three steps: initialize the bar object with txtProgressBar, update the bar
Functions
11•13
STATISTICAL COMPUTING AND R PROGRAMMING
with setTxtProgressBar, and terminate the bar with close. The next function, prog_test, modifies
sleep_test to include those three commands.
prog_test <- function(n){ result <- 0
progbar <- txtProgressBar(min=0,max=n,style=1,char="=")
for(i in 1:n){
result <- result + 1 Sys.sleep(0.5)
setTxtProgressBar(progbar,value=i)
}
close(progbar) return(result)
}
Before the for loop, you create an object named progbar by calling txtProgressBar with four
arguments. The min and max arguments are numeric values that define the limits of the bar. In
this case, you set max=n, which matches the number of iterations of the impending for loop.
The style argument (integer, either 1, 2, or 3) and the char argument (character string, usually a
single character) govern the appearance of the bar. Setting style=1 means the bar will simply
display a line of char; with char="=" it’ll be a series of equal signs.
Once this object is created, you have to instruct the bar to actually progress during execution with
a call to setTxtProgressBar. You pass in the bar object to update (progbar) and the value it should
update to (in this case, i). Once complete (after exiting the loop), the progress bar must be
terminated with a call to close, passing in the bar object of interest. Import and execute prog_test,
and you’ll see the line of "=" drawn in steps as the loop completes.
R> prog_test(8)
[1] 8
The width of the bar is, by default, determined by the width of the R console pane upon execution of
the txtProgressBar command. You can customize the bar a bit by changing the style and char
arguments. Choosing style=3, for example, shows the bar as well as a “percent completed” counter.
Some packages offer more elaborate options too, such as pop-up widgets, but the textual version is
the simplest and most universally compatible ver- sion across different systems.
You can store objects like these before and after some code and then compare them to see how
11•14
STATISTICAL COMPUTING AND R PROGRAMMING
much time has passed. Enter this in the editor:
t1 <- Sys.time()
Sys.sleep(3)
t2 <- Sys.time() t2-t1
Now highlight all four lines and execute them in the console.
Functions
11•15