简体   繁体   中英

How to create multiple xts objects from one xts object

I have created an 'xts' object from a data frame - the data frame was loaded from a 'csv' file.

The 'xts' object looks like so :-

            entitycode,usage
2016-01-01  1,16521
2016-01-01  2,6589
2016-01-02  1,16540
2016-01-02  2,6687
2016-01-03  1,16269
2016-01-03  2,6642

There are a total of 1462 records in it - 731 each for each of the entitycodes 1 and 2 from 01/01/2016 through to 31/12/2017 with a frequency of 1 day.

Entitycode 1 & 2 refer to different regions say 'region1' and 'region2'.

Is there a way to create separate 'xts' objects (variables) for entitycodes 1 & 2 (or 'region1' and 'region2') each with 731 rows with names like 'region1_xts' and 'region1_xts'?

Best regards

Deepak

I would recommend split ting the xts object resulting in a list of xts objects

split(xts, xts$entitycode)
#$`1`
#           entitycode usage
#2016-01-01          1 16521
#2016-01-02          1 16540
#2016-01-03          1 16269
#
#$`2`
#           entitycode usage
#2016-01-01          2  6589
#2016-01-02          2  6687
#2016-01-03          2  6642

You can then use functions of the *apply family to easily operate on the different list elements (ie the xts objects).


Sample data

df <- read.csv(text =
    "      date,entitycode,usage
2016-01-01,  1,16521
2016-01-01,  2,6589
2016-01-02,  1,16540
2016-01-02,  2,6687
2016-01-03,  1,16269
2016-01-03,  2,6642", header = T)

mat <- as.matrix(df[, -1])
rownames(mat) <- df[, 1]
colnames(mat) <- colnames(df)[-1]

xts <- as.xts(mat)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM