DataScience Classroomnotes 24/Dec/2021

R conditional statements

  • function to check if the number is even or odd
check.even <- function(n){
  if (n >=0 ){
    is_even <- (n %% 2 == 0)
    return(is_even)

  }else {
    print("invalid")
    return(NULL)
  }

}

check.even(-1)
check.even(2)
check.even(3)
  • The last statement will be returned automatically by R functions
check.even <- function(n){
  if (n >=0 ){
    is_even <- (n %% 2 == 0)

  }else {
    print("invalid")
    is_even <- NULL
  }
  is_even
}

check.even(4)

Preview

  • Using switch
    Preview
  • Refer Here for the R sample code written

Looping Constructs

Examples

  • Write a function in R to
  • Check the number is prime or not
is.prime <- function(number) {
if (number >= 2){
# finding the numbers to check 
all_numbers <- 2:(number-1)
mod_results <- number%%all_numbers
if (any(mod_results == 0)){
    return(FALSE)
}
    else {
    return(TRUE)
    }
}
}

is.prime(7)
is.prime(9)
  • print all the numbers in given range
is.prime <- function(number) {
if (number >= 2){
    # finding the numbers to check 
    all_numbers <- 2:(number-1)
    mod_results <- number%%all_numbers
    if (any(mod_results == 0)){
    return(FALSE)
    }
    else {
    return(TRUE)
    }
}
}

prime_numbers <- function(numbers) {
results <- c()
for (number in numbers){
    if(is.prime(number) == TRUE) {
    results <- append(results, number)
    }
}
return(results)
}

prime_numbers(100:1000)

  • Refer Here to view the code
  • Write a function to find the N highest values from vector
# find the nth highest value
nth.highest <- function(numbers, n) {
return (sort(numbers, decreasing = TRUE)[n])
}


values <- c(100,45,23,34,46,57,102)
nth.highest(values, 3)
nth.highest(values,2)
  • Write a function to remove NA elements from vector
# removing NA items from vector
remove.na <- function(values) {
return(values[!is.na(values)])
}

prices <- c(30.5, 31.5, NA, 30.5, 30.74, NA, 31)

prices <- remove.na(prices)
prices
  • We can use na.omit function as well
  • Write R code to filter the vector by some values
items <- c("apples", "oranges", "mangoes", "banana", "apples", "oranges", "mangoes", "banana", "apples", "oranges", "mangoes", "banana")

filter_by <- c("apples", "mangoes")

items[ items %in% filter_by]
  • Write a R function to simulate a coin flip n times
coin.filp <- function(size=1) {
return(sample(c("H", "T"), replace = TRUE, prob = c(0.5, 0.5), size = size))
}

coin.filp(100)
coin.filp()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner