R语言学习(6)-流程控制和循环

来源:互联网 发布:苹果日历同步数据消失 编辑:程序博客网 时间:2024/05/02 19:43
流程控制和循环
1.流程控制
        if和else
> if(TRUE)message("TRUE")
TRUE
> if(FALSE)message("FALSE")

if(FALSE)
{
message("FALSE")
}else
{
message("TRUE")
}
TRUE

        多分支switch函数
> (greek<-switch("gamma",alpha=1,beta=sqrt(4),gamma={
a<-sin(pi/3)
4*a^2
}
))
[1] 3  

> switch(
3,
"one",
"two",
"three",
"four"
)
[1] "three"

2.循环
        重复循环
            repeat函数:使用break跳出循环
                                 使用next跳过当前迭代
            while循环
            for循环
> for(i in 1:5) message("i=",i)
i=1
i=2
i=3
i=4
i=5

3.高级循环
            replicate函数能调用表达式数次
> replicate(5,runif(1))
[1] 0.7449666 0.8121744 0.1391714 0.4133810 0.8871107

            lapply函数
> prime_factor <- list(two = 2,three = 3, four = c(2,2),five=5,six=c(2,3))
lapply(prime_factor,unique)
$two
[1] 2
$three
[1] 3
$four
[1] 2
$five
[1] 5
$six
[1] 2 3


1 0