Siti Sal
Siti Sal

Reputation: 119

Generate 4-digit years format from as.date()

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

Answers (4)

G. Grothendieck
G. Grothendieck

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

Edgar Cutar Junior
Edgar Cutar Junior

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

Kerry Jackson
Kerry Jackson

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

Roman Luštrik
Roman Luštrik

Reputation: 70643

You should try %Y. See ?strptime.

Upvotes: 2

Related Questions