条件语句
if语句
只有if没有else,那么条件是FALSE时就什么都不做。
> rm(list = ls())
> i = -1
> if (i<0) print('up')
[1] "up"
> if (i>0) print('up')
有else。
> i =1
> if (i>0){
+ print('+')
+ } else {
+ print("-")
+ }
[1] "+"
ifelse函数
> i =1
> ifelse(i>0,"+","-")
[1] "+"
> x=rnorm(3)
> ifelse(x>0,"+","-")
[1] "+" "+" "-"
多个条件
i = 0
if (i>0){
print('+')
} else if (i==0) {
print('0')
} else if (i< 0){
print('-')
}
ifelse(i>0,"+",ifelse((i<0),"-","0"))
循环语句
For循环
> x <- c(5,6,0,3)
> s=0
> for (i in x){
+ s=s+i
+ print(c(i,s))
+ }
[1] 5 5
[1] 6 11
[1] 0 11
[1] 3 14
> x <- c(5,6,0,3)
> s = 0
> for (i in 1:length(x)){
+ s=s+x[[i]]
+ print(c(x[[i]],s))
+ }
[1] 5 5
[1] 6 11
[1] 0 11
[1] 3 14
如何保存结果?
> s = 0
> result = list()
> for(i in 1:length(x)){
+ s=s+x[[i]]
+ result[[i]] = c(x[[i]],s)
+ }
> result
[[1]]
[1] 5 5
[[2]]
[1] 6 11
[[3]]
[1] 0 11
[[4]]
[1] 3 14
> do.call(cbind,result)
[,1] [,2] [,3] [,4]
[1,] 5 6 0 3
[2,] 5 11 11 14
隐式循环
apply
apply(X, MARGIN, FUN, …) 其中X是数据框/矩阵名; MARGIN为1表示行,为2表示列,FUN是函数
> rm(list = ls())
> test<- iris[1:6,1:4]
> apply(test, 2, mean)
Sepal.Length Sepal.Width Petal.Length Petal.Width
4.9500000 3.3833333 1.4500000 0.2333333
> apply(test, 1, sum)
1 2 3 4 5 6
10.2 9.5 9.4 9.4 10.2 11.4
lapply
对列表/向量中的每个元素(向量)实施相同的操作
> test <- list(x = 36:33,y = 32:35,z = 30:27)
> test
$x
[1] 36 35 34 33
$y
[1] 32 33 34 35
$z
[1] 30 29 28 27
> lapply(test,mean)
$x
[1] 34.5
$y
[1] 33.5
$z
[1] 28.5
> lapply(test,fivenum)
$x
[1] 33.0 33.5 34.5 35.5 36.0
$y
[1] 32.0 32.5 33.5 34.5 35.0
$z
[1] 27.0 27.5 28.5 29.5 30.0
sapply
简化lapply()结果,直接返回矩阵或向量
> test
$x
[1] 36 35 34 33
$y
[1] 32 33 34 35
$z
[1] 30 29 28 27
> sapply(test,mean)
x y z
34.5 33.5 28.5
> sapply(test,fivenum)
x y z
[1,] 33.0 32.0 27.0
[2,] 33.5 32.5 27.5
[3,] 34.5 33.5 28.5
[4,] 35.5 34.5 29.5
[5,] 36.0 35.0 30.0
> class(sapply(test,fivenum))
[1] "matrix" "array"