R language loops and conditional execution

最后发布时间:2020-05-08 11:45:19 浏览量:

1. Conditional execution

if (expr_1) expr_2 else expr_3

score <- 70
if(score>90){
  message("you are very good")
}else if(score<90 && score>80){
  message("keep going")
}else{
  message("you must work hard")
}

# > you must work hard

This has the form ifelse(condition, a, b) and returns a vector of the same length as condition, with elements a[i] if condition[i] is true, otherwise b[i] (where a and b are recycled as necessary).

b <- c(98,85,95,85,66,77)
ifelse(b>=90,"excellent",ifelse(b>80,"good","average"))

# > "excellent" "good" "excellent" "good" "average" "average"  

2. Repetitive execution

2.1 for loops

for (name in expr_1) expr_2

for loop find the first 16 numbers of Fibonacci

n_fib <- 16
fib <- numeric(n_fib)
fib[1:2] = c(1,1)
for(i in 3:n_fib){
  fib[i] <- fib[i-1] + fib[i-2]
}

# >  1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

2.2 while

while (condition) expr

Fibonacci within 1000

fib <- c(1,1)
while(sum(tail(fib,2))<1000){
  fib <- c(fib,sum(tail(fib,2)))
}

# >   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

2.3 repeat

repeat expr

Fibonacci within 1000

fib <- c(1,1)
repeat{ # while(true)
  if(sum(tail(fib,2))>1000){
    break;
  }
  fib <- c(fib,sum(tail(fib,2)))
}

# >   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

3.Try not to use loops in R

Add two vectors with a length of 100 million

x <- 1:1e8
system.time(z <- x+x,gcFirst = TRUE)

# > user  system elapsed 
   0.227   0.129   0.355 

The vector takes only 0.46 seconds

system.time({
  for(i in 1:1e8){
   y=i+i    
  }
},gcFirst = TRUE)

# > user  system elapsed 
  8.969   0.113   9.081 

The loop takes 9.018 seconds