Conditional execution:
or
Another example:
Oneliner:
Beware!
if() Statementsif inside an if
ifelse() Functionheight <- c(69, 71, 67, 66, 72, 71, 61, 65, 73, 70, 68, 74)
if (height > 69){
print("tall")
} else {
print("short")
}Error in if (height > 69) {: the condition has length > 1
[1] "short" "tall" "short" "short" "tall" "tall" "short" "short" "tall"
[10] "tall" "short" "tall"
For more complicated cases we can use apply()
The following functions are useful for terminating a function call or just printing a warning message:
return()mySign <- function(x) {
if(x < 0) return("Negative")
if(x > 0) return("Positive")
return("Zero")
}
mySign(x = 13)[1] "Positive"
Note: return("Zero") not reached
stop()stop() means “error”
Note: return(x/y) not reached
warning()warning() just prints a warning message.
myRatio <- function(x, y) {
if(y == 0) warning("Attempt made to divide by 0")
return(x/y)
}
myRatio(x = 3, y = 0)Warning in myRatio(x = 3, y = 0): Attempt made to divide by 0
[1] Inf
R can divide by zero, it returns special value Inf
Repeat (iterate) an R statement
Stopping a loop:
for, while and repeat loopsdata.framecoins <- data.frame(Coin = c("penny", "quarter", "nickel", "quarter", "dime", "penny"),
Year = c(1943, 1905, 1889, 1960, 1937, 1900),
Mint = c("Den", "SF", "Phil", "Den", "SF", "Den"),
Condition = c("good", "fair", "excellent", "good", "poor", "good"),
Value = c(12.00, 55.00, 300.00, 40.00, 18.00, 28.00),
Price = c(15.00, 45.00, 375.00, 25.00, 20.00, 20.00))
coins Coin Year Mint Condition Value Price
1 penny 1943 Den good 12 15
2 quarter 1905 SF fair 55 45
3 nickel 1889 Phil excellent 300 375
4 quarter 1960 Den good 40 25
5 dime 1937 SF poor 18 20
6 penny 1900 Den good 28 20
Calculate the mean of each column:
data.frame ColumnsApplying a function to an object
apply()lapply()sapply()tapply()apply() requires 3 arguments:
1, 2, or c(1,2)( )) [,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Margin 1 to apply to the rows:
Margin 2 to apply to the columns:
[,1] [,2] [,3] [,4] [,5]
[1,] 1.000000 2.449490 3.316625 4.000000 4.582576
[2,] 1.414214 2.645751 3.464102 4.123106 4.690416
[3,] 1.732051 2.828427 3.605551 4.242641 4.795832
[4,] 2.000000 3.000000 3.741657 4.358899 4.898979
[5,] 2.236068 3.162278 3.872983 4.472136 5.000000
Remember:
“Simplify” lapply output:
patients <- data.frame("group"=paste('grp',
c(1,1,1,1,1,2,2,2,2,2),sep='-'),
"outcome"=rnorm(10))
#10 random normally distributed values
patients group outcome
1 grp-1 0.36335899
2 grp-1 -2.10322749
3 grp-1 -0.46796604
4 grp-1 0.81349481
5 grp-1 -1.88003678
6 grp-2 -0.48965553
7 grp-2 -0.02886587
8 grp-2 -1.10973330
9 grp-2 -0.18656796
10 grp-2 0.67209573
grp-1 grp-2
-0.6548753 -0.2285454