上节课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]#返回list的第二部分内容
[[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]#返回list第二部分的第一和二个元素,默认按列
[1] 1 5
> mylist[[2]][1:2,3]#返回list第二部分的第一和二行的第三列
[1] 3 7
> mylist[[2]][1:2,]#返回list第二部分的第一和二行所有元素
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
基本操作
>, >=, <, <=, ==, !=, x | y, x & y
控制流
循环语句
尽量避免使用For-Loop和While-Loop
> #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
条件语句
If statement、If-else statement和switch
switch语法:switch(expression, conditions)
> i = 1
> if(i == 1){
+ print("Hello World")
+ }
[1] "Hello World"
> i = 2
> if(i == 1){
+ print("Hello World!")
+ }else{
+ print("Goodbye World!")
+ }
[1] "Goodbye World!"
> 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"
自定义函数
如果function要写return要带()
curve第一个参数为一个function
> 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"