STA3050 Lec4笔记
1、创建函数
se<-function(x){
n<-length(x) # find the sample size
return(sd(x)/sqrt(n))
}
#这里的n是局部变量
创建函数的另一种写法
se<-function(x){sd(x)/sqrt(length(x))}
2、&和&&都代表and,但&对应整个向量,返回值为向量,&&仅对应向量第一个元素,返回一个值。 |和||同理(代表or)
> x=1:6
> (x > 2) & (x < 5)
[1] FALSE FALSE TRUE TRUE FALSE FALSE
> (x > 2) && (x < 5)
[1] FALSE
> x[(x>2) & (x<5)]
[1] 3 4
> x[(x>2) && (x<5)]
integer(0) #x[false]=inerger(0)
3、For语句
for (name in vector) { commands }
#如果就医有一个命令,可以省去大括号
4、If语句
if (condition) {
commands when TRUE # do if TRUE
} else {
commands when FALSE # do if FALSE
}
简化版
x <- 3
if (x > 2) y <- 2 * x else y <- 3 * x
5、While语句
while (condition) {statements}
6、Repeat语句
repeat { statements
...
if (condition) break
}
#break可以立刻终止整个循环,也可用在for/while语句中
next可以立刻终止某次循环,可以用在所有loop中