Movatterモバイル変換


[0]ホーム

URL:


Arithmetic {base}R Documentation

Arithmetic Operators

Description

These unary and binary operators perform arithmetic on numeric orcomplex vectors (or objects which can be coerced to them).

Usage

+ x- xx + yx - yx * yx / yx ^ yx %% yx %/% y

Arguments

x,y

numeric or complex vectors or objects which can becoerced to such, notablyarrays including matrices,or other objects for which methods have been written.

Details

The unary and binary arithmetic operators are generic functions:methods can be written for them individually or via theOps group generic function. (SeeOps for how dispatch is computed.)

If applied to arrays the result will be an array if this is sensible(for example it will not if the recycling rule has been invoked).

Logical vectors will be coerced to integer or numeric vectors,FALSE having value zero andTRUE having value one.

1 ^ y andy ^ 0 are1,always.x ^ y should also give the proper limit result wheneither (numeric) argument isinfinite (one ofInf or-Inf).

Objects such as arrays or time-series can be operated on thisway provided they are conformable.

For double arguments,%% can be subject to catastrophic loss ofaccuracy ifx is much larger thany, and a warning isgiven if this is detected.

%% andx %/% y can be used for non-integery,e.g.1 %/% 0.2, but the results are subject to representationerror and so may be platform-dependent. Mathematically, the answer to1 %/% 0.2 should be5, but because theIEC 60559representation of0.2 is a binary fraction slightly larger than0.2 most platforms give4.

Users are sometimes surprised by the value returned, for example why(-8)^(1/3) isNaN. Fordouble inputs,R makesuse ofIEC 60559 arithmetic on all platforms, together with the Csystem function ‘⁠pow⁠’ for the^ operator. The relevantstandards define the result in many corner cases. In particular, theresult in the example above is mandated by the C99 standard. On manyUnix-alike systems the commandman pow gives details of thevalues in a large number of corner cases.

Arithmetic on typedouble inR is supposed to be done in‘round to nearest, ties to even’ mode, but this does depend onthe compiler andFPU being set up correctly.

Value

Unary+ and unary- return a numeric or complex vector.All attributes (including class) are preserved if there is nocoercion: logicalx is coerced to integer and names, dims anddimnames are preserved.

The binary operators return vectors containing the result of the elementby element operations. If involving a zero-length vector the resulthas length zero. Otherwise, the elements of shorter vectors are recycledas necessary (with awarning when they are recycled onlyfractionally). The operators are+ for addition,- for subtraction,* for multiplication,/ fordivision and^ for exponentiation.

%% indicatesx mod y (“x modulo y”), i.e.,computes the ‘remainder’r <- x %% y, and%/% indicates integer division, whereR uses “floored”integer division, i.e.,q <- x %/% y := floor(x/y), as promotedby Donald Knuth, see the Wikipedia page on ‘Modulo operation’,and hencesign(r) == sign(y). It is guaranteed that(up to rounding error)

    x == (x %% y) + y * (x %/% y)

unlessy == 0 where the result of%% isNA_integer_ orNaN (depending on thetypeof of the arguments) or for some non-finitearguments, e.g., when the RHS of the identity aboveamounts toInf - Inf.

If either argument is complex the result will be complex, otherwise ifone or both arguments are numeric, the result will be numeric. Ifboth arguments are of typeinteger, the type of the result of/ and^ isnumeric and for the other operators itis integer (with overflow, which occurs at\pm(2^{31} - 1),returned asNA_integer_ with a warning).

The rules for determining the attributes of the result are rathercomplicated. Most attributes are taken from the longer argument.Names will be copied from the first if it is the same length as theanswer, otherwise from the second if that is. If the arguments arethe same length, attributes will be copied from both, with those ofthe first argument taking precedence when the same attribute ispresent in both arguments. For time series, these operations areallowed only if the series are compatible, when the class andtsp attribute of whichever is a time series (the same,if both are) are used. For arrays (and an array result) thedimensions and dimnames are taken from first argument if it is anarray, otherwise the second.

S4 methods

These operators are members of the S4Arith group generic,and so methods can be written for them individually as well as for thegroup generic (or theOps group generic), with argumentsc(e1, e2) (withe2 missing for a unary operator).

Implementation limits

R is dependent on OS services (and they onFPUs) for floating-pointarithmetic. On all currentR platformsIEC 60559 (also known as IEEE754) arithmetic is used, but some things in those standards areoptional. In particular, the support fordenormal akasubnormal numbers(those outside the range given by.Machine) may differbetween platforms and even between calculations on a single platform.

Another potential issue is signed zeroes: onIEC 60559 platforms thereare two zeroes with internal representations differing by sign. WherepossibleR treats them as the same, but for example direct outputfrom C code often does not do so and may output ‘⁠-0.0⁠’ (and onWindows whether it does so or not depends on the version of Windows).One place inR where the difference might be seen is in division byzero:1/x isInf or-Inf depending on the sign ofzerox. Another place isidentical(0, -0, num.eq = FALSE).

Note

All logical operations involving a zero-length vector have azero-length result.

The binary operators are sometimes called as functions ase.g.`&`(x, y): see the description of howargument-matching is done inOps.

** is translated in the parser to^, but this wasundocumented for many years. It appears as an index entry in⁠Becker, Chambers, and Wilks (1988),pointing to the help forDeprecated butis not actually mentioned on that page. Even though it had beendeprecated in S for 20 years, it was still accepted inR in 2008.

References

Becker RA, Chambers JM, Wilks AR (1988).The New S Language.Chapman and Hall/CRC, London.

Goldberg D (1991).“What Every Computer Scientist Should Know about Floating-point Arithmetic.”ACM Computing Surveys,23(1), 5–48.doi:10.1145/103162.103163.
Also available athttps://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html.

For theIEC 60559 (aka IEEE 754) standard:https://www.iso.org/standard/57469.html andhttps://en.wikipedia.org/wiki/IEEE_754.

On the integer division and remainder (modulo) computations,%%and%/%:https://en.wikipedia.org/wiki/Modulo_operation, and

Knuth DE (1972).The Art of Computer Programming, Volume 1: Fundamental Algorithms.Addison-Wesley.ISBN 978-0201038095.

See Also

sqrt for miscellaneous andSpecial for specialmathematical functions.

Syntax for operator precedence.

%*% for matrix multiplication.

Examples

x <- -1:12x + 12 * x + 3x %%  3 # is periodic  2 0  1  2 0  1 ...x %% -3 #  (ditto)    -1 0 -2 -1 0 -2 ...x %/% 5x %% Inf # now is defined by limit (gave NaN in earlier versions of R)## Illustrating PR#18677, see above1 %/% print(0.2, digits=19)

[Packagebase version 4.6.0Index]

[8]ページ先頭

©2009-2025 Movatter.jp