rmatrixtime-seriesxts

How to divide the columns in a time series by their first value in R?


I have the code below working. But there must be a better way.

file <- "http://s3.amazonaws.com/assets.datacamp.com/production/course_1127/datasets/tmp_file.csv"
x <- read.csv(file = file)
ts <- xts(x = x,  order.by = as.Date(rownames(x), "%m/%d/%Y"))
cd=coredata(ts)
for (j in 1:length(names(ts)))  cd[,j]<-cd[,j]/cd[1,j]
for (j in 1:length(names(ts))) ts[,j]<-cd[,j]

Solution

  • We can use apply to divide each column by its first value:

    file <- "http://s3.amazonaws.com/assets.datacamp.com/production/course_1127/datasets/tmp_file.csv"
    x <- read.csv(file = file)
    
    library(xts)
    ts <- xts(x = x, order.by = as.Date(rownames(x), "%m/%d/%Y"))
    
    ts <- apply(ts, 2, function(x) x / x[1])
    
               a        b
    2015-01-02 1 1.000000
    2015-02-03 2 1.333333