# Create indices for two time series values in R

I am trying to compare two time series in R to assess how closely they correlate by plotting them on a line graph. To avoid having two separate axes for the data, I want to make an index of each value, to plot the changes of the values since date X by plotting the indices rather than the raw data.

Data looks like this:

```Table 1.
Month   A      B
Jan     3883   151831
Feb     3626   154070
Mar     4346   163550
Apr     3439   155674
```

Desired output looks like this:

```Table 2.
Month   A      A.index   B        B.index
Jan     3883   100       151831   100
Feb     3626   93.38     154070   101.47
Mar     4346   111.92    163550   107.71
Apr     3439   88.56     155674   102.53
```

I can achieve this in excel by exporting table 1 to excel and adding a column for A.index and B.index and using a calculation to determine the change from the the index number of 100. Assuming that A is in column B, then I simply:

```=(cn)/c\$2*100
```

Where cn is column C row n, c\$2 is the original value and 100 is the index number.

However, I'd like to know how to achieve the same thing in R, so that I can wrap it in a function, as this will be something I need to do semi-regularly.

Cheers Tom

Using tranform(), this is simple as can be. The key line is actually pretty similar to the Excel code, and should be self-explanatory.

```df <- read.table(text="Month   A      B
Jan     3883   151831
Feb     3626   154070
Mar     4346   163550

df <- transform(df, A.index=100*A/A[1], B.index=100*B/B[1])
df
#   Month    A      B   A.index  B.index
# 1   Jan 3883 151831 100.00000 100.0000
# 2   Feb 3626 154070  93.38141 101.4747
# 3   Mar 4346 163550 111.92377 107.7185
# 4   Apr 3439 155674  88.56554 102.5311
```