R语言:循环

2019-02-18 14:52:46 浏览数 (1)

这里介绍五种R语言的循环语法,分别是:

  • for
  • if
  • repeat
  • which
  • while

for

代码语言:javascript复制
samples<- c(rep(1:10))
samples
##  [1]  1  2  3  4  5  6  7  8  9 10
for(thissample in samples){
  print(thissample)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
for ( thissample in samples){
  str <- paste(thissample,"is current sample",sep = " ")
  print (str)
}
## [1] "1 is current sample"
## [1] "2 is current sample"
## [1] "3 is current sample"
## [1] "4 is current sample"
## [1] "5 is current sample"
## [1] "6 is current sample"
## [1] "7 is current sample"
## [1] "8 is current sample"
## [1] "9 is current sample"
## [1] "10 is current sample"
for( thissample in samples){
  if (thissample == 3)
    break
  str<-paste(thissample,"is current sample" , sep = " ")
  print (str)
}
## [1] "1 is current sample"
## [1] "2 is current sample"
for(thissample in samples){
  if (thissample %% 2 == 0)
    next 
  str<-paste(thissample,"is current sample",sep = " ")
  print(str)
}
## [1] "1 is current sample"
## [1] "3 is current sample"
## [1] "5 is current sample"
## [1] "7 is current sample"
## [1] "9 is current sample"
end<-length(samples)
begin <- end -2
for(thissample in begin:end){
  str<-paste(thissample,"is current sample",sep = " ")
  print(str)
}
## [1] "8 is current sample"
## [1] "9 is current sample"
## [1] "10 is current sample"

if

代码语言:javascript复制
samples<-c(rep(1:10))
samples
##  [1]  1  2  3  4  5  6  7  8  9 10
for(thissample in samples){
  if (thissample %% 2 != 0)
    next
  else
    print(thissample)
}
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
ret<-ifelse(samples>6,2,1)
ret
##  [1] 1 1 1 1 1 1 2 2 2 2

repeat

代码语言:javascript复制
total<-0
repeat{
  total<-total  1;
  print(total);
  if (total > 6)
    break;  
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
total
## [1] 7

which

代码语言:javascript复制
which(letters == "h")
## [1] 8
data(BOD)
BOD
##   Time demand
## 1    1    8.3
## 2    2   10.3
## 3    3   19.0
## 4    4   16.0
## 5    5   15.6
## 6    7   19.8
which(BOD$demand == 16)
## [1] 4
x<-matrix(1:9,3,3)
x
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
which(x %% 3 == 0,arr.ind = TRUE) #返回位置
##      row col
## [1,]   3   1
## [2,]   3   2
## [3,]   3   3
which(x %% 3 == 0,arr.ind = FALSE) # 返回数
## [1] 3 6 9

while

代码语言:javascript复制
x<-1
while(x<5){
  x<-x 1
  print(x)
}
## [1] 2
## [1] 3
## [1] 4
## [1] 5
x<-1
while(x<5){
  x<-x 1
  if(x == 3)
    break
  print(x)
}
## [1] 2
x<-1
while(x<5){
  x<-x 1
  if(x == 3)
    next
  print (x)
}
## [1] 2
## [1] 4
## [1] 5

0 人点赞