Home > database >  creat a Count function in R
creat a Count function in R

Time:12-07

I am trying to solve the following task

Write a function that counts the number of odd and even numbers in a vector and provides three outputs (the outputs is supposed to tell me how many odd and even numbers there are in the vector)

CodePudding user response:

vector <- c(1,2,3,4,5,6,7,8,9)

Not sure what you mean by three outputs as you've listed two but this will count the number of odd and even numbers in a vector as well as give the sum.

myfunc <- function(x) {
  addmargins(setNames(table(x %% 2), c("even", "odd")),1)
}

Output:

> myfunc(vector)
even  odd  Sum 
   4    5    9 

CodePudding user response:

Based on the feedback of the rpevious answer, here one has the solution:

> vec <- c(1,2,3,4,5,6,7) # Test Vector

> evenoddsumm <- function(vec) {
    even <- vec[vec/2 == round(vec/2,0)]
    odd <- vec[vec/2 != round(vec/2,0)]
    result <- c(paste("There are ",length(even)," even numbers.", sep = ""),
                paste("There are ",length(odd)," odd numbers.", sep = ""),
                paste("There are ",length(odd)," odd numbers and ",length(even)," even numbers.", sep = ""))
    return(result)
  }


> evenoddsumm(vec)
[1] "There are 3 even numbers."                  "There are 4 odd numbers."                  
[3] "There are 4 odd numbers and 3 even numbers."

The approach is consider an even as a number that remains integer when divided by 2, which means even/2 is equal round(even/2)

  • Related