R: Applying a Function to an xts Object -


i have xts object:

anchor_date <- as.date("2016-04-19") end_date <- as.date(anchor_date + years(5)) number_days <- end_date - anchor_date   xts_object <- xts(rep(na, number_days + 1), as.date(anchor_date) + 0:number_days) 

i have function takes square of time between date , start date in years:

time_squared_func <- function(start_date, date) {   time_squared <- as.numeric(((date - start_date) / 365) ^ 2)   return (time_squared) } 

i want apply function xts object, using constant start_date = first day in series, have date argument date in row of xts object. result should 0 in first row, gradually increasing 1 on 2017-04-19, 4 on 2018-04-19 etc...

https://codereview.stackexchange.com/questions/39180/best-way-to-apply-across-an-xts-object

this suggests vapply faster apply or lapply, if possible using vapply ideal, working fine.

thank you.

using lapply , rbind

require(lubridate)  anchor_date <- as.date("2016-04-19") end_date <- as.date(anchor_date + years(5)) number_days <- end_date - anchor_date   xts_object <- xts(rep(na, number_days + 1), as.date(anchor_date) +  0:number_days)  time_squared_func <- function(start_date, date) {   time_diff = as.numeric(date - start_date)   time_squared <- (time_diff / 365) ^ 2   return (time_squared) } 

pass first date , each row index (date) time_squared_func function , rbind output final result

first_date = as.date(index(first(xts_object)))  ts_lapply = do.call(rbind,lapply(as.date(index(xts_object)),function(x) time_squared_func(first_date ,x) ) )  ts_xts = xts(ts_lapply,as.date(index(xts_object)))  for(i in 1:5) print(ts_xts[anchor_date+years(i)])            # [,1] # 2017-04-19    1            # [,1] # 2018-04-19    4            # [,1] # 2019-04-19    9                # [,1] # 2020-04-19 16.02193               # [,1] # 2021-04-19 25.0274 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -