mardi 25 mai 2021

When to place if inside the for loop and when not to do so

Why is the if else condition outside the for loop for(v in views). Why still is R able to read the the whole vector, e.g. linkedin.

linkedin <- c(16, 9, 13, 5, 2, 17, 14)         
facebook <- c(17, 7, 5, 16, 8, 13, 14)

interpret <- function(num_views) {        
  if (num_views > 15) {        
    print("You're popular!")         
    return(num_views)         
  } else {        
    print("Try to be more visible!")         
    return(0)         
  }
}

interpret_all <- function(views, return_sum=TRUE) {        
  count <- 0         

  for (v in views) {        
    count<-count+interpret(v)         
  }         

  if (return_sum==TRUE) {        
    return(count)         
  } else {        
    return("null")         

  }         
}         

Aucun commentaire:

Enregistrer un commentaire