سؤال

If I have a set of daily data, I want to get the minimum value for each month, and the date on which that value occurred. If I use the apply.monthly function, it gives me the minimum value, but the corresponding date is the end of every month, not the date when it actual occurred. How can I get the correct date?

library(xts)
#create sample data
dates<-seq(from=as.Date("1970-01-01"),to=as.Date("1970-12-31"),by=1)
x<-sample(1:365,365)
ts<-xts(x,dates)

#apply function
monthly.mins<-apply.monthly(ts,min)
monthly.mins
هل كانت مفيدة؟

المحلول

apply.monthly uses period.apply, and always indexes at the endpoint of each period. If you want different behavior, you need to use more general functions.

In this case, you can use the lapply(split(), ...) idiom with a custom function:

do.call(rbind, lapply(split(ts,"months"), function(x) x[which.min(x)]))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top