Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use scale in R for a precise lookback period?

Tags:

r

center

scale

I would like to scale & center some data, I know how to scale it with

(scale(data.test[,1],center=TRUE,scale=TRUE))

I have 365 observations (one year), and would like to scale & center my data for a lookback period of 20 days.

For example I would like to do that: "Normalized for a 20day lookback period" means that to scale my first value 01/01/2014 (dd/mm/yy) I have to scale it only with the 20 days before. So with values from the 11/12/13 to 31/12/13 And for the 02/01/14 scale it from the 12/12/13 to the 01/01/14 etc

Normalize the data would be = ( the data - the mean of all data / standard deviation of all the data (see my code )

But as I want "20 day lookback period" means that I have to only look at the 20 last values it would be = (the data - the mean of the 20 previous data) / standard deviation of the 20 previous data

I thought to make a loop maybe? As I am very new to R I don't know how to write a loop in R or even if there is a better way to do what I want... If you could help me with this.

like image 429
Coralie maire Avatar asked Oct 30 '22 23:10

Coralie maire


1 Answers

You want a 20 days lookback : lookback<-20 data.scale<-c() #Create a vector for the data scaled for(i in lookback:nrow(data)){ mean<-mean(data[i-(lookback-1):i,1],na.rm=T) sd<-sd(data[i-(lookback-1):i,1],na.rm=T)*sqrt(((lookback-1))/lookback) data.scale<-c(data.scale,(data[i,1]-mean)/sd) }

for the row 20 you want to normalized with the data from day 1 to day 20, day 21 from day 2 to day 21 and so on...

like image 145
Christophe D. Avatar answered Nov 11 '22 17:11

Christophe D.