Extracting nth day of monthly data in r

ⅰ亾dé卋堺 提交于 2019-12-02 09:42:37

问题


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!


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/27587276/extracting-nth-day-of-monthly-data-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!