如何从 apply.monthly 函数中提取日期 [英] How to extract dates from apply.monthly function
问题描述
如果我有一组每日数据,我想获得每个月的最小值,以及该值发生的日期.如果我使用 apply.monthly
函数,它会给我最小值,但对应的日期是每个月的月底,而不是实际发生的日期.我怎样才能得到正确的日期?
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
使用 period.apply
,并且 always 索引在每个时期的终点.如果你想要不同的行为,你需要使用更通用的函数.
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.
在这种情况下,您可以使用带有自定义函数的 lapply(split(), ...)
习惯用法:
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)]))
这篇关于如何从 apply.monthly 函数中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!