In: Computer Science
R programming language
A) Create a function that accepts two arguments, an integer and a vector of integers. It returns the count of the number of occurrences of the integer in the input vector.
1]Input: num_count <-function ??? 2]Input: num_count(2,c(1,1,2,2,3,3))
2] Output: 2
3] Input: num_count(1,c(1,1,2,2,3,1,4,5,5,2,2,1,3))
3] Output : 4
B) Create a function that accepts 3 integer values and returns their sum. However, if an integer value is evenly divisible by 3, then it does not count towards the sum. Return zero if all numbers are evenly divisible by 3. Hint: You may want to use the append() function.
1] Input: summer <- function???
2] Input: summer(7,2,3)
2] Output: 9
3] Input: summer(3,6,9)
3] Output:0
4] Input: summer(9,11,12)
4] Output: 11
C)Create a function that will return TRUE if an input integer is prime. Otherwise, return FALSE. You may want to look into the any() function
1]Input: prime_check <- function ???
2]Input: prime_check(2)
2]Output: TRUE
3] Input: prime_check(5)
3] Output: TRUE
4] Input: prime_check(4)
4] Output: FALSE
5]Input: prime_check (237)
5] Output: FALSE
6] Input: prime_check(131)
6] Output: TRUE
#function to calculate the count of given number in a
vector
num_count <- function(num, v){
#check the vaues equal to num in the vector
#calculate the sum
sum(v == num)
}
#call the function
num_count(2, c(1, 1, 2, 2, 3, 3))
#function to calculate the sum of number which are not divisible
by 3
summer <- function(num1, num2, num3){
#create a vector with the three numbers
vals <- c(num1, num2, num3)
#calculate the sum if they are not divisible by 3
sum(vals[vals %% 3 != 0])
}
#call the function
summer(3, 6, 9)
#function to calculate whether a given number is prime
number
prime_check <- function(num){
#if the number is less than 2 reutrn false
if(num < 2)
{
return(FALSE)
}
#if the number is true return true
if(num == 2)
{
return(TRUE)
}
#create a vector from 2 to num - 1
vals <- seq(2, num - 1)
#check if there are any factors
#if there are no factors then it is a prime number
!any(vals %% num == 0)
}
#call the function
prime_check(7)