【发布时间】:2019-08-22 16:42:41
【问题描述】:
我有 1970 年到 2019 年的每日库存数据子集。我的目标是在一列中获取每年发生最小值的日期,在另一列中获取最小值。我可以遍历子集以使用“foreach”、“.combine=rbind”、“lapply”和“which.min”来构建我想要但我无法获得的行列表以这种方式超出索引的日期。
mindates <- foreach(i = 1:length(GSPC_yearly), .combine=rbind) %do% {
# I would like to be able to attach the corresponding row label date from the index to this code
spyannmin<-as.numeric(lapply(GSPC_yearly[[i]]$GSPC.Low,min))
spyannmindate<-(lapply(GSPC_yearly[[i]]$GSPC.Low,which.min))
# Or be able to bind this code row wise because its output already includes the row label date from the index of the source data. This is only giving me the result of the last [[i]], i want a table of rows with all the [[i]]'s
spyannmindexdate<-GSPC_yearly[[i]][spyannmindate,3]
result.data<-c(spyannmin, spyannmindate,spyannmindexdate)
}
head(mindates,3)
spyannmindexdate
这给了我这样的输出...
GSPC.Low
result.1 68.61 101 68.61
result.2 89.34 227 89.34
result.3 100.87 2 100.87
# But I would like the date to appear where the result.# appears or in a new column, I'm not sure which would be better.
GSPC.Low
2019-01-03 2443.96
# Or I would like this data exactly, but pasted with the respective row from each yearly subset of the larger source data. Again I want output that includes the row for each year.
如果我只使用“which.min”来获取行索引,那么我可以获得日期和最小值但没有“lapply”我不知道如何使用“.combine=rbind”构建表
所以我有两种方法可以解决我的问题,但每种方法都缺少一个关键要素。我将不胜感激任何一个解决方案。两者的解决方案将有助于提高我对 r 编程的理解。提前谢谢你。
【问题讨论】: