Dr. Mark Gardener 


Home  
Home > Data Analysis > R Monographs > The 3 Rs: Reading, wRiting and aRithmetic > Part 3. Arithmetic



R: MonogRaphsA series of essays on random topics using R: The Statistical Programming LanguageR is a powerful and flexible beast. Getting started using R is not too difficult and you can learn to start using R in an afternoon. However, mastering R takes rather longer! These monographs are my way of exploring various topics in a completely unstructured manner. Tips & Tricks for R  An Introduction to R Writer's Bloc  Courses 

The 3 Rs: Reading data 
The 3 Rs: Reading, wRiting and aRithmeticPart 3. ArithmeticI remember reading about the 3 Rs as the most important topics in education: reading writing and arithmetic. I thought it would be interesting to examine these in an R context e.g. reading data, writing data and doing maths. This page is all about arithmetic, part 1 was about Reading, part 2 was about Writing. Index for Part 3.
Part 2. Writing  MonogRaphs Index 

Use R like a calculator  IntroductionYou can think of R as like a giant calculator. It has a great capacity for mathematical operations. In this article I'll look at some of the more basic ones, to give a flavour of what basic arithmetic you can do. 

Basic math operators: Exponents use: ^ Note order of operations: Use sqrt() or x^0.5 for square root. Modulo: %% 
OperatorsIn the main your arithmetic is going to involve adding up, dividing, subtracting and multiplication. These things are all carried out using basic operators that are familiar to everyone: +  * / and (). The order of the operators is important. R will evaluate your maths in a set order. multiplication (*) and division (/) are evaluated first. Then addition (+) and subtraction (). As well as this basic order, things inside parentheses () will be evaluated before anything "outside" the parentheses (still in the */+ order). So, remember this running order when you type your maths e.g. 7 + 4 * 11 As well as the basic operators there are some "extras". Powers (i.e. exponents) are designated using the caret (^) character. These are evaluated before any of the other operators. For example: 2^2 ; 2^3 ; 2^4 If you want a fractional power you enclose this in parentheses e.g. 64^(1/2) A square root is simply a power of 0.5 e.g. x^0.5 but there is a special command sqrt() to deal with this. x = c(9, 16, 25, 36, 49, 59) You can use the % symbol to compute modulo (%%) and integer division (%/%) like so: 16 %/% 3 So, you have 16 ÷ 3 giving 5 and 1 remainder. 

Matrix multiplication via: Matrix cross products: equivalent to: t(x) %*% y 
Matrix operationsThere are a bunch of commands associated with matrix math. Matrix multiplicationMultiply two matrices using the %*% operator. ## Make some matrices (x = cbind(1,1:3,c(2,0,1))) Matrix Cross ProductsYou can compute the cross product using the %*% operator and the t() command. Alternatively the crossprod() and tcrossprod() commands can do the job: (x = cbind(1,1:3,c(2,0,1))) 

Miscellaneous matrix math commands: backsolve() 
Other matrix mathsThere are various other commands associated with matrix math. They are not really operators (except %o%) as such but I'll list them here:


Logical operators: AND & && Logical operators work with comparison operators to produce TRUE FALSE result. 
Logical OperatorsSome operators are used to provide a logical result (i.e. TRUE or FALSE). Logical ANDThe & operator is used for the logical AND in an elementwise manner. If you double up the operator && you perform the operation on only the first element. Logical ORThe vertical bar  is used for the logical OR in an elementwise manner. If you double up the operator  you perform the operation on only the first element. Logical NOTThe ! operator is used for the logical NOT. Logical Exclusive ORThe command xor(x, y) acts as an exclusive OR operator. The logical operators work in conjunction with other operators (comparisons) to produce results. So, look at the examples in the next section. 

Comparisons: Often used with Logical Operators 
ComparisonsComparison operators allow you to compare elements. These are often used in conjunction with the logical operators.
Here are some simple examples: ## Make some vectors yy = c(2, 3, 6, 5, 3) 

Use any() to match any element in an object Use all() to match all elements in an object 
Selection and MatchingThe comparison and logical operators are used to obtain TRUE/FALSE results. However, they are not always the best choice for selection. There are times when you are looking for a single logical result but using regular operators either fails, or produces more than one. In these cases the selection commands are helpful. They aren't strictly mathematical operators but it is helpful to be aware of them. Additionally the isTRUE() command can "force" a single logical as a result. Match any item in an objectUse the any() command to return a single TRUE result if any element meets the specified criteria. Match all items in an objectUse the all() command to return a single TRUE result if all elements meet the specified criteria. 

Commands for returning single logical result: identical() 
Compare objectsThe identical() command compares two items and returns a TRUE if they are exactly equal. The all.equal() command is similar but with a bit more tolerance. (yy = c(2, 3, 6, 5, 3)) # Make a vector Note that you can use identical(TRUE, x) in lieu of isTRUE(x), where x is the condition to test. 

Use which() to return an index of which elements match criteria. 
Selection with nonlogical resultYou can use the which() command to obtain an "index" instead of a logical result. The command works in conjuction with the comparison and logical operators but returns a result that indicates which elements match your criteria. yy = c(2, 3, 6, 5, 3) 

Complex numbers have an imaginary part and have class "complex" Make and "test" complex items using: Commands for complex math: Regular math operators also work on complex numbers. 
Complex numbersComplex numbers are those with "imaginary" parts. You can make complex numbers using the complex() and as.complex() commands, whilst the is.complex() command provides a quick logical test to see if an object has the class "complex". R has several commands that can deal with complex numbers.
Here are some simple examples: ## Make some complex numbers z0 = complex(real = 1:8, imaginary = 8:1) Besides these special commands, the regular math operators work on complex numbers: z0 + z1 

Precision and rounding: abs() Commands work on most numeric objects. On logicals TRUE returns 1 and FALSE returns 0 
RoundingThere are various commands that deal generally with precision and rounding.
These are all fairly obvious; here are some examples: ## Make some values yy = log(2^(2:6)) These commands work on most numeric objects (e.g. data.frame, vector, matrix, table). If you have logical objects you'll return 1 for a TRUE and 0 for a FALSE. 

Add an exponent to a number to create a scientific format number. Use e or E Use format() command to "force" printing in scientific format or not. Result is a text object. Use options(scipen = n) to change default number handling. 
Scientific FormatYou can enter numbers using an exponent to make it easier to deal with very large or very small values. The exponent is indicated by the letter e or E. You can use the  sign to indicate a negative exponent. The + sign can be omitted. You must not leave a space between the value and the exponent. You can only add an exponent to a numeric value and not to a named object. 1e3 Values are generally "printed" by R in regular format but sometimes they will appear in scientific format. This makes no difference to your calculations but sometimes you want the result to be displayed in scientific format and at other times not. There are two ways to achive the result you want. The simplest way to present your results objects in an appropriate format is to use the format() command. You simply set scientific = TRUE to prepare an object in that format (set FALSE to use regular format). The downside to this is that the object is prepared as a text result, which might be inconvenient. The other way is to alter the options() and to set the scipen option. The default is 0. Negative values tend to produce scientific notation and positive values are less likely to do so. ## Make some values yy = c(1, 10, 100, 1000, 10000, 100000) You may need to tweak the values of scipen but in general the number of digits in the result is your guideline. 

Extremes: Use order() to make index if you want nth largest or nth smallest values. 
ExtremesThe largest and smallest items can be extracted using max() and min() commands repsectively. These commands produce a single value as the result. The range() command produces two values, the smallest and largest, in that order. ## Set random number generator set.seed(99) If you want the 2nd largest, or the 3rd smallest (for example) then you need to use the order() command to get an "index". Set the sort order to decreasing = FALSE (the default) to get the smallest values, set decreasing = TRUE to get the largest values. xx 

Logarithms: Default base is natural. 
LogarithmsLogarithms and their reverse (antilogs?) are dealt with using the log() and exp() commands repsectively. The default base is the natural log (e) but you can specify the base explicitly. There are also several convenience commands:
Using the commands is fairly simple. log(1:4) # Natural log 

Trigonometry: cos() acos() Hyperbolic functions: cosh() acosh() Angles in radians 
TrigonometryR has a suite of commands that carry out trigonometric functions.
The commands work out the basic functions and also hyperbolic equivalents. Angles are in radians (a right angle is pi/2 radians). Here are some simple examples using the cosine: cos(45) # Angle in radians 

Summation Add items using sum() Get product of items using product() Logical TRUE = 1 prod(x:y) = factorial(y) Related to gamma() function: prod(x:y) 
SummationThere are various commands associated with lists of values (that is list in a general sense, not an R list object). Adding thingsThe sum() command returns the sum of all the numbers specified. This works for most R objects, including data.frame, matrix and vectors. Logical values are treated as 1 (TRUE) or 0 (FALSE). NA items are treated as 0. You can "ignore" NA items using na.rm = TRUE as a parameter in the command. Multiplying thingsThe prod() command returnd the product of all the numbers specified, that is each value multiplied by the "next". This works for most R objects, including data.frame, matrix and vectors (items are taken columnwise for data.frame objects). Logical values are treated as 1 (TRUE) or 0 (FALSE). NA items are treated as 0. You can "ignore" NA items using na.rm = TRUE as a parameter in the command. v = 1:9 The factorial() command is similar to prod(). With prod() you specify prod(x:y) as a sequence, whilst in factorial() you specify factorial(y). If you provide more than one value, you end up with multiple results: factorial(3) # i.e. 3 * 2 * 1 You can also use the gamma() command, which equates to factorial(x1). Essentially prod(x:y) = gamma(y+1) = factorial(y). 

Cumulative functions: Operate on vector and matrix objects directly. 
Cumulative functionsThere are several cumulative functions builtin to R. These determine sum, product, maximum and minimum.
The commands operate on numeric objects, usually vector or matrix objects. The commands work on data.frame objects but compute results per column. The commands do not work directly on lists (but you can use the lapply() command). v = 1:9 It is possible to make custom functions that calculate other cumulative results, but that is another story. 

There are many other mathematical functions in R. This has been a brief overview of some of the more "simple" arithmetic (although the foray into logic may not count as math).


Part 2. Writing  MongRaphs Index


See my Publications about statistics and data analysis. Writer's Bloc – my latest writing project includes R scripts Courses in data analysis, data management and statistics. 
My Publications about statistics and data analysis See my personal pages at GardenersOwn 

Follow me... 

Top  Home  MonogRaphs Index  Contact 