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 ¶metric){
+ 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"