Reputation: 119
I want to generate list of URL which looping from startDate to the endDate. However the valid URL written in 4-digit years and the result come out in 2-digit format. Here I'm using Lubridate package. I believe there are simpler one for this. How can I improve this code ? Thank you..
startDate <- as.Date("01-11-17", format="%d-%m-%y")
endDate <- as.Date("31-01-18",format="%d-%m-%y")
theDay <- startDate
while (theDay <= endDate)
{
dy <- as.character(theDay, format="%d")
month <- as.character(theDay, format = "%m")
year <- as.character(theDay, format ="%y")
link <- "http://weather.uwyo.edu/cgi-bin/sounding?"
address <-
paste0(link,year,"&MONTH=",month,"&FROM=",dy,"00&T0=",dy,"00&STNM=48657")
print(address)
theDay = theDay + 1
}
Upvotes: 0
Views: 918
Reputation: 269526
This can be done without a loop as follows. u is now a character vector of URLs.
link <- "http://weather.uwyo.edu/cgi-bin/sounding?"
params <- "region=naconf&TYPE=TEXT:LIST&YEAR=%Y&MONTH=%m&FROM=%d00&T0=%d00&STNM=48657"
fmt <- paste0(link, params)
u <- format(seq(startDate, endDate, by = "day"), format = fmt)
Upvotes: 2
Reputation: 78
You can simply use the function year() from the package lubridate. Below is the code:
startDate <- as.Date("01-11-17", format="%d-%m-%y")
year(startDate)
#[1] 2017
Upvotes: 2
Reputation: 1871
Since you are using lubridate
, just use the year
function:
year <- year(theDay)
library(lubridate)
startDate <- as.Date("01-11-17", format="%d-%m-%y")
endDate <- as.Date("31-01-18",format="%d-%m-%y")
theDay <- startDate
while (theDay <= endDate)
{
address <-
paste0("http://weather.uwyo.edu/cgi-bin/sounding?",
year(theDay),
"&MONTH=",sprintf("%02d", month(theDay)) ,
"&FROM=",sprintf("%02d", day(theDay)) ,"00&T0=",sprintf("%02d", day(theDay)) ,
"00&STNM=48657")
print(address)
theDay = theDay + 1
}
Upvotes: 1