下面展示一些关于R中的控制流语句的具体运用。
#if函数
a <- -1
if(a<0)result = 0 else
if (a<1)result = 1 else
result = 2
result
#switch函数
switch(2, mean(1:10),1:5,1:10)
#输出后三个列表或值中的第二个,超过则输出空值
y <- "fruit"
switch(y, fruit = "apple", vegetable = "brocolli", meat = "beef")
#switch自身就是可以进行直接输出的函数
#for函数
n <- c(2,5,10)
for (i in n) {
x <- sqrt(i)
cat("sqrt(",i,"):",x,"\n")
#cat函数很好用,比print直接打印可调节的东西更多,建议使用cat
}
#while循环
x <- c(1,1)
i <- 3
while (i <= 10) {
x[i] <- x[i-1] + x[i-2]
i <- i+1
}
x
#repeat-break循环,谨慎使用
pv <- c(1,1,2,3,1,1,15,7,18)
i <- 1
results <- ""
repeat{
if(i > length(pv))break
if(pv[i] <= 5) results[i] <- "初级用户" else
if(pv[i] <= 15) results[i] <- "中级用户"else
results[i] <- "高级用户"
i <- i+1
}
results
> #if函数
> a <- -1
> if(a<0)result = 0 else
+ if (a<1)result = 1 else
+ result = 2
> result
[1] 0
>
> #switch函数
> switch(2, mean