# 循环结构,向量化编程,泛函式编程
# for循环
for (x in c(-2, 3,0,4)) {
print(x)
y = abs(x)
z = y^3
print(z)
print(“......”)
}
# while循环
v1 <- 1:5
i <- 1
While(i <= length(v1)) {
Print(i)
Print(sum(v1[1:i]))
I = i + 1
Print(i)
Print(“###”)
}
# 示例
df <- data.frame(c1 =2:5,
c2 = 4:7,
c3 = -19:-16)
for (i in 1:nrow(df)) {
print(sum(df[j, ]))
j = j +1
}
# next
# break
# 条件结构
a <- 7
if(a > 6) {
print(“a > 6”)
} else
print(“a <= 6”)
}
a <- 5
if(a > 6) {
print(“a > 6”)
} else
print(“a <= 6”)
}
a <- 2
if(a > 6) {
print(“a > 6”)
} else if (a > 3){
Print(“a > 3”)
} else {
print(“a <= 3”)
}
s = 45
if( s %% 2 2 == 0) {
print(“s是偶数,”)
} else {
print(“s是奇数”)
}
if (s %% 2 != 1) {
print(“s是偶数,”)
} else {
print(“s是奇数”)
}
ifelse (s %% 2 == 0, “偶数”,“奇数”)
# 函数构建
f1 <- function(aug1) {
res1 <- 1:aug1
res2 <- prod(res1) # 乘积
return(res2) # 函数过程构建结束,下面不会运行
}
f1(aug1 = 10) # 得到10的阶乘
f1(10) # 两个都可以,参数名称自己可以随便设置,不写参数名称时注意顺序
f2 <- function(aug1, aug2=4 ){
res <- aug1 + aug2
return(res)
}
f2(34) # 不设定的话会利用历史记录的,这里会用f1
f2(34, 5)
注:学习视频来源于B站,特别感谢R语言数据分析从入门到进阶(已完结。第6部分可视化作图请移步至 R语言数据可视化)_哔哩哔哩_bilibili