R语言之控制流语句

R里通常用符号”<-”代替其它语言里的”=”来作赋值符号。因为“=”敲起来简单。但要切记两者在某些时候是有区别的。字面上的解释,可以认为”<-”是赋值,”=”是传值。在函数调用中,func(x=1)与func(x<-1)是有区别的,前者调用完后变量x不会被保留,而后者会在工作区里保留变量x=1。再如length(x=seq(1,10))计算完成后x不会被保留,而length(x<-seq(1,10))计算完后你会在工作区里发现x这个变量。

> for(i in 1:10)
+ print("hello")
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello"

>  while(i<=10){
+ sum<-sum+i
+ i<-i+1
+ 
+ }
> sum
[1] 55

>  a<-65
> if(a>60)print("A")
[1] "A"
> if(a<60)print("A")else print("false")
[1] "false"
> ifelse(a>60,print("passed"),print("a"))
[1] "passed"
[1] "passed"
> outcome<-ifelse(a>60,"a","b")
> outcome
[1] "a"
> players <- c("Ronaldo","beckham")
> for (i in players)
+ print(
+ switch(i,
+ Rondldo = "c",
+ beckham ="d",
+ messi = "L"
+ )
+ )
NULL
[1] "d"

> x<- 0.0
> s<- 0
> n<- 5
> for(i in 1:n)
+ x<- 2*x+1
> s=s+x
> s
[1] 31
> s=0
> x=
+ 0
>  for(i in 1:n)
+ {
+ x<- 2*x+1
+ s=s+x
+ }
> s
[1] 57
> ifelse(x>=60,print("large"),print("small"))
[1] "small"
[1] "small"

> myStats<-function(x,parametric=TRUE,print=FALSE){
+ if(parametric){
+ center<-mean(x);spread<-sd(x)
+ }else{
+ center <-median(x);spead<-mad(x)
+ }
+ if(print &parametric){
+ cat("Mean=",center,"\n","SD=",spread,"\n")
+ }else if(print&!parametric){
+  cat("Mean=",center,"\n","SD=",spread,"\n")
+  }
+  result<-list(center=center,spread=spread)
+  return(result)
+ }
> set.seed(1234)
>  x<-rnorm(500)
>  y<-myStats(x)
> y
$center
[1] 0.001838821

$spread
[1] 1.034814
> mydata<-function(type="long"){
+  switch(type,
+ long= format(Sys.time(),"%A%B%Y"),
+ short = format(Sys.time(),"%m-%d-%y"),
+ cat(type,"is not recongnized type\n")
+ )
+ }
> mydata()
[1] "星期三五月2020"
> mydata("short")
[1] "05-27-20"
> mydata("long")
[1] "星期三五月2020"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值