1. Last Lecture - List
> x = matrix(1:20, nrow=5, ncol=4, byrow=TRUE)
> swim = read.csv("http://www.macalester.edu/~kaplan/ISM/datasets/swim100m.csv")
> mylist=list(swim,x) # 创建mylist,包含swim和x
> mylist[2]
[[1]]
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
[5,] 17 18 19 20
> mylist[[2]][2] #返回mylist第2部分的第2个元素(默认竖向)
[1] 5
> mylist[[2]][3]
[1] 9
> mylist[[2]][1:2] #返回mylist第2部分的前2个元素
[1] 1 5
> mylist[[2]][1:2,3] #1,2两行,第3列
[1] 3 7
> mylist[[2]][1:2,] #1,2两行
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
2. Operators
( "three value logic"-三值逻辑 )
>, >=, <, <=, ==, !=(不等于), x | y(或), x & y(且)
3. Control Flow
3.1 Repetition and looping
Looping constructs repetitively execute a statement or series of statements until a condition is not true. These include the for and while structures.
> #For-Loop
> for(i in 1:10){ # 1到10
+ print(i)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
> #While-Loop
> i = 1
> while(i <= 10){ # 1到10
+ print(i)
+ i=i+1
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
3.2 Conditional Execution
In conditional execution, a statement or statements are only executed if a specified condition is met. These constructs include if, if-else, and switch.
> #If statement
> i = 1
> if(i == 1){
+ print("Hello World")
+ }
[1] "Hello World"
> #If-else statement
> i = 2
> if(i == 1){
+ print("Hello World!")
+ }else{
+ print("Goodbye World!")
+ }
[1] "Goodbye World!"
> #switch
> #switch(expression, cnoditions)
> feelings = c("sad", "afraid")
> for (i in feelings){
+ print(
+ switch(i,
+ happy = "I am glad you are happy",
+ afraid = "There is nothing to fear",
+ sad = "Cheer up",
+ angry = "Calm down now"
+ )
+ )
+ }
[1] "Cheer up"
[1] "There is nothing to fear"
4. User-defined Function
One of greatest strengths of R is the ability to add functions. In fact, many of the functions in R are functions of existing functions.
> myfunction = function(x,a,b,c){
+ return(a*sin(x)^2 - b*x + c)
+ }
> curve(myfunction(x,20,3,4),xlim=c(1,20))

> curve(exp(x),xlim=c(1,20))

> myfeeling = function(x){
+ for (i in x){
+ print(
+ switch(i,
+ happy = "I am glad you are happy",
+ afraid = "There is nothing to fear",
+ sad = "Cheer up",
+ angry = "Calm down now"
+ )
+ )
+ }
+ }
> feelings = c("sad", "afraid")
> myfeeling(feelings)
[1] "Cheer up"
[1] "There is nothing to fear"