1

I'm facing a problem with making columns using loop.

I have a xts dataset and it's second-by-second data.

It's start from

2014-09-01 00:00:00 104.172
2014-09-01 00:00:01 104.170
2014-09-01 00:00:02 104.170
2014-09-01 00:00:03 104.170
2014-09-01 00:00:04 104.170
2014-09-01 00:00:05 104.170

and end up with

2014-09-30 03:59:43 109.312
2014-09-30 03:59:44 109.312
2014-09-30 03:59:45 109.312
2014-09-30 03:59:46 109.312
2014-09-30 03:59:47 109.312
2014-09-30 03:59:48 109.313

I would like to make nth day columns from this data set. So I did something like this

for(i in 1:30){ask[i] <- ask[.indexmday(ask) == i]}

but it didn't work. Instead, I got a warning

number of items to replace is not a multiple of replacement length

When I do

asksep1 <- ask[.indexmday(ask) == 1]

it works and I can get Sep-1st data. So I think there's something wrong with my loop.

How can I do that? Thanks for any help!

Roki
  • 13
  • 5

2 Answers2

3

It seems like you want split.xts. Using the data from akrun's answer:

lst <- split(ask, "days")
sapply(lst, nrow)
# [1] 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400
#[13] 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400
#[25] 86400 86400 86400 86400 86400 14400
Community
  • 1
  • 1
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
0

You could create a list and store the subset for each day in a list. It might be useful when the number of rows are not the same for each day.

days <- unique(.indexmday(ask))
lst <- vector('list', length(days))
for(i in seq_along(days))lst[[i]] <- ask[.indexmday(ask)==days[i]]

sapply(lst, nrow)
# [1] 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400
#[13] 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400 86400
#[25] 86400 86400 86400 86400 86400 14400

data

val <- rnorm(840000*3, 110)
indx <- seq(as.POSIXct('2014-09-01 00:00:00', format='%Y-%m-%d %H:%M:%S'),
    length.out=840000*3, by='sec')
library(xts)
ask <- xts(val, order.by=indx)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, it worked! Since I didn't have enough time to solve, you answer helped me a lot! – Roki Dec 21 '14 at 07:26