Home > Software design >  even and odd number in matrix
even and odd number in matrix

Time:12-13

I want to write a code for a matrix and return the number of odd and even with using function.

for example, I run this code for odd and even but I don't know how to determine the number of even and odd in the matrix.

x = 1:9
u = matrix(x, 3, 3)
fu = function(u){
   if(u%%2 ==0)(return("joz"))
   else{
     return("fard")
   }
 }
fu(3)
[1] "fard"

CodePudding user response:

If you are looking to get counts of how many are odd/even

odd_even <- function(x) c("odd"=sum(x%%2), "even"=sum(!x%%2))

E.g. this gives 3 and 6

x <- matrix(c(1,3,5,1,7,9,8,8,2), nrow=3)
odd_even(x)

CodePudding user response:

Here is a base R one-line solution.

even_odd <- function(x) setNames(table(x %% 2), c("even", "odd"))

a <- matrix(1:9, 3)

even_odd(a)
#even  odd 
#   4    5 
  •  Tags:  
  • r
  • Related