even or odd in R, modulo operation in R, remainder in R

How to determine if the number is even or odd in R

You can tell if the number is even or odd in R programming by looking at the reminder after the number is divided by 2. If the remainder equals 0, it is an even number, otherwise, it is an odd number. There is a nifty way to get the reminder after division in R by using its syntax.

 

Here are five numbers.

1:5

#[1] 1 2 3 4 5

Although R has multiple functions that start with “is” and can indicate certain content, there is nothing for even or odd number detection. For example, with the function is.na you can see which elements are missing and use that like in this scenario.

Despite that, here is what you can do. By using the %% operator, you can do a modulo operation in R that returns a reminder.

1:5 %% 2

#[1] 1 0 1 0 1

You can detect if the reminder equals 0 and the number is even or if it does not equal 0 and the number is odd.

1:5 %% 2 == 0

#[1] FALSE  TRUE FALSE  TRUE FALSE

ifelse(1:5 %% 2 == 0, "even", "odd")

#[1] "odd"  "even" "odd"  "even" "odd"

 

If you want to extract records or data frame rows that contain odd or even numbers in R, you can do that with a filter like this.

head(mtcars)

#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1



require(dplyr)

mtcars %>% 
  filter(carb %% 2 != 0) %>% 
  head()

#                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#Merc 450SE     16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
#Merc 450SL     17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
#Merc 450SLC    15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3

 

Here is another practical use case. If the number is known to be odd or even, you can use that in formatting. This post contains the result of ggplot2 with the multi-color x-axis tick labels. If the year is an odd number, it will appear in one color, otherwise in a different one.

Multi-level axis labels in R, ggplot2 axis labels in multiple rows, multi-row R plot axis labels, axis labels in multiple lines in R


Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *