Reputation: 1527
What is the double percent (%%
) used for in R?
From using it, it looks as if it divides the number in front by the number in back of it as many times as it can and returns the left over value. Is that correct?
Out of curiosity, when would this be useful?
Upvotes: 33
Views: 134910
Reputation: 226087
The "Arithmetic operators" help page (which you can get to via ?"%%"
) says
‘
%%
’ indicates ‘x mod y’
which is only helpful if you've done enough programming to know that this is referring to the modulo operation, i.e. integer-divide x
by y
and return the remainder. This is useful in many, many, many applications. For example (from @GavinSimpson in comments), %%
is useful if you are running a loop and want to print some kind of progress indicator to the screen every nth iteration (e.g. use if (i %% 10 == 0) { #do something}
to do something every 10th iteration).
Since %%
also works for floating-point numbers in R, I've just dug up an example where if (any(wts %% 1 != 0))
is used to test where any of the wts
values are non-integer.
Upvotes: 57
Reputation: 931
The result of the %% operator is the REMAINDER of a division,
Eg. 75%%4 = 3
I noticed if the dividend is lower than the divisor, then R returns the same dividend value.
Eg. 4%%75 = 4
Cheers
Upvotes: 13
Reputation: 41
%%
in R return remainder
for example:
s=c(1,8,10,4,6)
d=c(3,5,8,9,2)
x=s%%d
x
[1] 1 3 2 4 0
Upvotes: 4