# R Language Addition and subtraction

## Example

The basic math operations are performed mainly on numbers or on vectors (lists of numbers).

1. Using single numbers

We can simple enter the numbers concatenated with `+` for adding and `-` for subtracting:

``````> 3 + 4.5
#  7.5
> 3 + 4.5 + 2
#  9.5
> 3 + 4.5 + 2 - 3.8
#  5.7
> 3 + NA
# NA
> NA + NA
# NA
> NA - NA
# NA
> NaN - NA
# NaN
> NaN + NA
# NaN
``````

We can assign the numbers to variables (constants in this case) and do the same operations:

``````> a <- 3; B <- 4.5; cc <- 2; Dd <- 3.8 ;na<-NA;nan<-NaN
> a + B
#  7.5
> a + B + cc
#  9.5
> a + B + cc - Dd
#  5.7
> B-nan
# NaN
> a+na-na
# NA
> a + na
# NA
> B-nan
# NaN
> a+na-na
# NA
``````

2. Using vectors

In this case we create vectors of numbers and do the operations using those vectors, or combinations with single numbers. In this case the operation is done considering each element of the vector:

``````> A <- c(3, 4.5, 2, -3.8);
> A
#   3.0  4.5  2.0 -3.8
> A + 2 # Adding a number
#   5.0  6.5  4.0 -1.8
> 8 - A # number less vector
#   5.0  3.5  6.0 11.8
> n <- length(A) #number of elements of vector A
> n
#  4
> A[-n] + A[n] # Add the last element to the same vector without the last element
#  -0.8  0.7 -1.8
> A[1:2] + 3 # vector with the first two elements plus a number
#  6.0 7.5
> A[1:2] - A[3:4] # vector with the first two elements less the vector with elements 3 and 4
#  1.0 8.3
``````

We can also use the function `sum` to add all elements of a vector:

``````> sum(A)
#  5.7
> sum(-A)
#  -5.7
> sum(A[-n]) + A[n]
#  5.7
``````

We must take care with recycling, which is one of the characteristics of `R`, a behavior that happens when doing math operations where the length of vectors is different. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated. In this case a Warning is show.

``````> B <- c(3, 5, -3, 2.7, 1.8)
> B
#   3.0  5.0 -3.0  2.7  1.8
> A
#   3.0  4.5  2.0 -3.8
> A + B # the first element of A is repeated
#   6.0  9.5 -1.0 -1.1  4.8
Warning message:
In A + B : longer object length is not a multiple of shorter object length
> B - A # the first element of A is repeated
#   0.0  0.5 -5.0  6.5 -1.2
Warning message:
In B - A : longer object length is not a multiple of shorter object length
``````

In this case the correct procedure will be to consider only the elements of the shorter vector:

``````> B[1:n] + A
#   6.0  9.5 -1.0 -1.1
> B[1:n] - A
#   0.0  0.5 -5.0  6.5
``````

When using the `sum` function, again all the elements inside the function are added.

``````> sum(A, B)
#  15.2
> sum(A, -B)
#  -3.8
> sum(A)+sum(B)
#  15.2
> sum(A)-sum(B)
#  -3.8
`````` PDF - Download R Language for free