Skip to content

R programming language

R is a language and environment for statistical computing. Learn its vector arithmetic through adjacent price returns, indexing, recycling and missing values.

R is a programming language and software environment for statistical computing and graphics. In quant work, it lets you turn observations into numerical objects, calculate returns, fit models and inspect results in a repeatable analysis. R includes statistical facilities and can be extended with packages; the language is distinct from an editor used to write it. R Core's introduction describes this environment.

The letter R here names the language. It does not mean a return variable or the regression goodness-of-fit statistic R-squared.

Start with an ordered vector

A numeric vector is an ordered collection of numbers. c() combines values, <- assigns an object to a name, and ordinary arithmetic can operate element by element. This vectorisation makes a whole sequence of calculations readable without writing a loop. These basic operations are documented in Vectors and assignment.

Suppose an asset has fictional prices of USD 100, 110 and 99 at three consecutive observations. There are no dividends, fees or missing observations. Prices are in chronological order, and the two holding periods have equal length. The simple price return for each period is the ending price divided by its preceding price, minus one.

prices <- c(100, 110, 99) stopifnot(length(prices) >= 2, all(is.finite(prices)), all(prices > 0)) returns <- prices[-1] / prices[-length(prices)] - 1 print(round(returns, 4)) # [1] 0.1 -0.1 print(round(prod(1 + returns) - 1, 4)) # [1] -0.01
The output returns are decimals: 0.1 means +10%, and -0.1 means −10%. prices[-1] drops the first observation, leaving 110 and 99; prices[-length(prices)] drops the last, leaving 100 and 110. The matching positions therefore represent the two adjacent periods. Both vectors have the same length. The code creates returns without changing prices.
Three fictional USD prices, 100 then 110 then 99, form two aligned ratios: 110 over 100 minus one gives +10%, and 99 over 110 minus one gives −10%. Across both periods the price return is −1%.
Three fictional USD prices, 100 then 110 then 99, form two aligned ratios: 110 over 100 minus one gives +10%, and 99 over 110 minus one gives −10%. Across both periods the price return is −1%.
Two adjacent returns from three price observations. Equal positive and negative percentage returns leave the final price below the starting price.

The combined return is −1%, because the growth factors multiply: 1.1×0.9=0.991.1\times0.9=0.99. Adding the two percentage returns would hide the loss.

Three semantics worth checking

Positions begin at one. For a plain vector, prices[1] selects the first value. Negative indices exclude positions; they do not count backward from the end. See the official extraction rules.
Different lengths may still produce a result. Base-R arithmetic recycles the shorter vector. When its length divides the longer length exactly, this can happen without a warning:
print(c(1, 2, 3, 4) + c(10, 20)) # [1] 11 22 13 24
Here the second vector repeats as 10, 20, 10, 20. In a portfolio calculation, an unintended repeat could assign the wrong quantities to assets. Check lengths and the meaning of each position; successful execution does not establish financial alignment. The arithmetic documentation specifies recycling and the warning for fractional recycling.
Missing values need a policy. NA marks an unavailable value. For example, the default arithmetic mean propagates it, while na.rm = TRUE explicitly removes it:
observed_returns <- c(0.02, NA, 0) print(mean(observed_returns)) # [1] NA print(mean(observed_returns, na.rm = TRUE)) # [1] 0.01
The second result describes only the two observed returns. Removing a missing price before calculating returns can also join observations across a gap, changing the holding period. Retain dates and decide what missing data means for the analysis. The mean() reference documents its default and missing-value option.

Running the analysis again

Save the commands in a script and run them in a clean session, keeping the input data and package versions with the analysis. If you introduce random simulation, set a seed with set.seed() before drawing values. This example uses only base R and no randomness; its code was executed with R 4.5.1. Decimal output is rounded for display because floating-point arithmetic need not represent decimal fractions exactly.

Sources

Last updated
  • r
  • statistical computing
  • quant programming
  • financial data
← Back to the glossaryBack to top ↑