课程源代码:https://github.com/miwu8512/IntroToR
视频地址: https://www.youtube.com/watch?v=rPj5FsTRboE&list=PLBTcf4SwWEI9_kCOJ-1o-Jwr-_Qb6bkeg
Lecture 3
1 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[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] ##用[[]]申明所用的list
[1] 5
> mylist[[2]][1:2]
[1] 1 5
> mylist[[2]][1:2,3]
[1] 3 7
> mylist[[2]][1:2,]
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
2 Operators 判断语句
, >=, <, <=, ==, !=, x|y(x或y), x&y(x和y)
3 Control flow 流程控制
3.1 repetition and looping 循环语句
Looping constructs repetitively execute a statement or series of statments until a condition is not true. Including the for and while structures.
> #For-loop
> for(i in 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){
+ 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
- for 和while运行速度慢,大数据量时尽量避免使用,尽量用向量和方程解决
3.2 Conditional execution 条件语句
In conditonal execution, a statement or statements are only executed if a specified condition is met. Including if, if-else, 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 statement
> 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 = "Chear up",
+ angry = "Calm down now"
+ )
+ )
+ }
[1] "Chear up"
[1] "There is nothing to fear"
4 User-defined Function 自定义函数
One of the 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))
> myfeeling = function(x){
+ for(i in x){
+ print(
+ switch(i,
+ happy = "I am glad you are happy",
+ afraid = "There is nothing to fear",
+ sad = "Chear up",
+ angry = "Calm down now"
+ )
+ )
+ }
+ }
> feelings = c("sad","afraid")
> myfeeling(feelings)
[1] "Chear up"
[1] "There is nothing to fear"