[英]Looping through dates in R
我正在嘗試為開始和結束日期創建一個循環來運行這個 function:
startdates <- c("2003-10-01", "2004-10-01", "2005-10-01", "2006-10-01", "2007-10-01",
"2008-10-01", "2009-10-01",
"2010-10-01", "2011-10-01", "2012-10-01", "2013-10-01", "2014-10-01", "2015-10-01",
"2016-10-01","2017-10-01", "2018-10-01", "2019-10-01")
enddates <- c("2004-09-30", "2005-09-30", "2006-09-30", "2007-09-30", "2008-09-30",
"2009-09-30","2010-09-30", "2011-09-30", "2012-09-30", "2013-09-30", "2014-09-30",
"2015-09-30", "2016-09-30","2017-09-30", "2018-09-30", "2019-09-30", "2020-09-30")
for(i in dates) {
statsOutput <- FUNCTIONHERE(siteNumber = "xxx",
startDate = startdates,
endDate = enddates)
}
我不確定如何設置此循環,以便它將在我的向量(開始日期和結束日期)中獲取開始日期和結束日期。 我無法列出我正在使用的 function,但它需要一個 siteNumber,進入 web 以獲取該站點的數據,然后使用 startDate 和 endDate 來了解要獲取的日期范圍。
我們可以遍歷其中任何一個的序列(假設兩者具有相同的length
)。 使用索引在循環中對相應的“開始日期”、“結束日期”進行子集化,並將 output 存儲在list
statsOutput <- vector('list', length(startdates))
for(i in seq_along(startdates)) {
statsOutput[[i]] <- FUNCTIONHERE(siteNumber = "xxx",
startDate = startdates[i],
endDate = enddates[i])
}
或者使用Map
可能更容易
statsOutput <- Map(FUNCTIONHERE, startDate = startdates, endDate = enddates,
MoreArgs = list(siteNumber = "xxx"))
我們將使用paste
作為 function fun
來使這個可執行文件。 用你擁有的任何東西替換它。
out
將是結果列表。 如果fun
創建標量並且您想要矢量結果,請將Map
替換為mapply
。
yr <- 2003:2019
st <- paste0(yr, "-01-01")
en <- paste0(yr, "-09-30")
fun <- paste
out <- Map(fun, "xxx", st, en, USE.NAMES = FALSE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.