![]() |
![]() |
![]() |
|
![]() |
|
![]() |
|
Modular arithmetic and rounding in R (February 1, 2007). Category: R software
In certain programming situations, you need to perform calculations involving division that produce whole numbers as a result. For example, if you divided 27 by 4, you would get 6.75, but if you were using whole numbers only, then your result would be 6 with a remainder of 3.
In R, the operator
%/%produces an integer division, and the operator%%computes the remainder. So in R, the result of19%/%4would be6and the result of19%%4would be3.Here's a practical example. Suppose you wanted to take the numbers 0 through 23 and place them in a matrix with 4 rows and 6 columns, filling the matrix row by row. Integer division will help you assign the rows
> 1+(0:23)%/%4
[1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6and modular artithmetic will help you assign the columns
> 1+(0:23)%%4
[1] 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4If you want to round a number to the nearest integer, use the
round()function. For numbers with fractional portions exactly equaling 0.5, this function always rounds to the even digit. Theround()function has an argument,digits, which allows you to round at a different level of precision. For example, usingdigits=2will round to the nearest hundredth, anddigits=-3will round to the nearest thousand.Other related functions that will produce integer results are
ceiling()which computes the closest integer that is larger than x,floor()which computes the closest integer that is smaller than x, andtrunc()which computes an integer by dropping the fractional portion.You would think that the last two functions produce the same results, and that is indeed true for positive numbers. But for negative numbers, dropping the fractional portion will actually produce a slightly larger value. Thus
floor(-9.1)equals-10, buttrunc(-9.1)equals-9.Related web pages:
This webpage was written by Steve Simon and was last modified on 07/08/2008.