R 流程控制与函数
1. 条件语句
x <- 10
if (x > 0) {
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}
2. 循环结构
- For Loop:
for (i in 1:5) { print(i) } - While Loop:
while (condition) { # do something } - Repeat Loop: 需要
break跳出。
3. 函数定义
my_function <- function(arg1, arg2) {
result <- arg1 + arg2
return(result)
}
4. apply 家族
apply, lapply, sapply, tapply - 向量化操作,比循环更高效。