REVISED: Saturday, March 2, 2013
In this tutorial, you will receive an introduction to writing R scripts.
I. WRITING R SCRIPTS
Go to the "tool bar" across the top of the screen, left mouse click "File", then left mouse click "New Script" and the “Untitled - R Editor” window will open for writing scripts. This is the Editor that comes with R and it is more than adequate for someone new to R.
A. R CONTROL STRUCTURES
Common control structures in R which allow you to control the flow of execution of a program when you are writing scripts include the following:
1. if, else: testing a condition. The else is optional.
2. for: execute a loop a fixed number of times.
3. while: execute a loop while a condition is true.
4. repeat: execute an infinite loop.
5. break: break the execution of a loop.
6. next: skip an iteration of a loop.
7. return: exit a function.
B. R CONTROL STRUCTURE EXAMPLES
R is case sensitive; and conditions are always evaluated from left to right.
1. if, else: testing a condition. The else is optional.
if ( condition1 ){
# do
condition1 statements
}else if( condition2 ){
# do
condition2 stattements
}else{
# do
else statements
}
2. for: execute a loop a fixed number of times.
x <- matrix(1:6, 2, 3)
> x
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
for (i in seq_len(nrow(x))){
for (j in seq_len(ncol(x))){
print(i)
}
}
[1] 1
[1] 1
[1] 1
[1] 2
[1] 2
[1] 2
3. while: execute a loop while a condition is true.
count <- 0
while (count < 10) {
print(count);
count <- count + 1
}
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
4. repeat: executes an infinite loop; and
5. break: breaks the execution of a loop.
A repeat loop is exited by calling a break.
x0 <- 1
tol <- 1e-8
repeat {
x1 <- computeEstimate() # computeEstimate() not included.
if (abs(x1 - x0) < tol) {
break
} else {
x0 <- x1
}
}
6. next: skip an iteration of a loop.
for (i in 1:100) {
if (i <= 30) {
# Skip the first 30 iterations.
next
}
# Do something here.
}
7. return: exit a function.
When a return is encountered the function exits and returns a given value.
In this tutorial, you have received an introduction to writing R scripts.
Elcric Otto Circle
-->
-->
-->
How to Link to My Home Page
It will appear on your website as:"Link to: ELCRIC OTTO CIRCLE's Home Page"
No comments:
Post a Comment