CUNY SPS DS_Challenge_R

Question 1

Complete the function below to return TRUE if a number is a prime, otherwise return FALSE:

#creating R function to accept a number and return TRUE if a number is a prime, otherwise return FALSE: 
is_prime <- function(num){
  
  if (num == 2) {
      TRUE
   } else if (any(num %% 2:(num-1) == 0)) {
      FALSE
   } else { 
      TRUE
   }
}
#Testing is prime function 
test_prime_num <- is_prime(6)
print(test_prime_num)
## [1] FALSE
print(is_prime(5))
## [1] TRUE

Question 2

Given a list of the following words, write code in R to filter the list to fruits that start with a vowel:

library(tidyverse)
library(stringr)
#Create a list of fruits as given in the question
fruit_list <- list('apple','pear','orange','banana','elderberry','strawberry')
paste0(fruit_list)
## [1] "apple"      "pear"       "orange"     "banana"     "elderberry"
## [6] "strawberry"
typeof(fruit_list)
## [1] "list"
#Using grep function to find the index of fruit in the list starting with vowels
fruits_with_vowel_index <- c(grep("^[aeiouy]", tolower(fruit_list)))
paste0(fruits_with_vowel_index)
## [1] "1" "3" "5"
typeof(fruits_with_vowel_index)
## [1] "integer"
#filter the list of fruits using index obtained from above operation
fruits_start_with_vowles <- fruit_list[fruits_with_vowel_index]
paste0(fruits_start_with_vowles)
## [1] "apple"      "orange"     "elderberry"
typeof(fruits_start_with_vowles)
## [1] "list"