Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-format xts data in R more efficiently?

Tags:

for-loop

r

xts

I have a xts object with series of moving average based on n period.

              3     5       8    10
2012-11-16 1.573333 1.598 1.61500 1.631
2012-11-19 1.543333 1.576 1.60125 1.617
2012-11-20 1.546667 1.562 1.58750 1.601
2012-11-21 1.523333 1.530 1.57000 1.583

I would like to reformat it to the following.

              ma     n
2012-11-16 1.573333  3
2012-11-16 1.598     5
2012-11-16 1.61500   8
2012-11-16 1.631     10
2012-11-19 1.543333  3
2012-11-19 1.576     5
2012-11-19 1.60125   8
2012-11-19 1.617     10
2012-11-20 1.546667  3
2012-11-20 1.562     5
2012-11-20 1.58750   8
2012-11-20 1.601     10
2012-11-21 1.523333  3
2012-11-21 1.530     5
2012-11-21 1.57000   8
2012-11-21 1.583     10

Currently, I am using a for loop, which I don't think is efficient enough in R.

> sma1
              3     5       8    10
2012-11-16 1.573333 1.598 1.61500 1.631
2012-11-19 1.543333 1.576 1.60125 1.617
2012-11-20 1.546667 1.562 1.58750 1.601
2012-11-21 1.523333 1.530 1.57000 1.583
>
> n <- c(3,5,8,10)
> count <- 0
> for(i in n) { 
+     tempsma <- cbind(rbind(sma1[,paste(i,sep="")]),paste(i,sep=""))
+     if (count == 0) {
+         sma2 <- tempsma 
+         count <- 1
+     } else {
+         sma2 <- rbind(sma2,tempsma)
+     }
+ }
> names(sma2) <- c("ma","n")
> sma2
                 ma  n
2012-11-16 1.573333  3
2012-11-16 1.598000  5
2012-11-16 1.615000  8
2012-11-16 1.631000 10
2012-11-19 1.543333  3
2012-11-19 1.576000  5
2012-11-19 1.601250  8
2012-11-19 1.617000 10
2012-11-20 1.546667  3
2012-11-20 1.562000  5
2012-11-20 1.587500  8
2012-11-20 1.601000 10
2012-11-21 1.523333  3
2012-11-21 1.530000  5
2012-11-21 1.570000  8
2012-11-21 1.583000 10

Since for loop in R is expensive, I am wondering if there is a more efficient way to perform the same task.

Thanks!

like image 309
user1839587 Avatar asked Jan 29 '26 19:01

user1839587


1 Answers

Here a solution using stack.

First I create a sample data:

> dat <- xts(data.frame(matrix(1:8,ncol=4)),Sys.time()+1:2)
> dat
                    X1 X2 X3 X4
2013-02-28 00:17:25  1  3  5  7
2013-02-28 00:17:26  2  4  6  8

Then , I put it in the long format using stack:

> data.frame(index(dat),stack(as.data.frame(coredata(dat))))
           index.dat. values ind
1 2013-02-28 00:17:25      1  X1
2 2013-02-28 00:17:26      2  X1
3 2013-02-28 00:17:25      3  X2
4 2013-02-28 00:17:26      4  X2
5 2013-02-28 00:17:25      5  X3
6 2013-02-28 00:17:26      6  X3
7 2013-02-28 00:17:25      7  X4
8 2013-02-28 00:17:26      8  X4
like image 160
agstudy Avatar answered Feb 01 '26 13:02

agstudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!