2

I am working with R trying to use the sprintf function to print multiple urls. The URL is in the form http://www.weather.unh.edu/data/year/day.txt. I want to print the url for each day of multiple years. I tried:

day <-c(1:365) year <-c(2001:2004) urls<- sprintf("http://www.weather.unh.edu/data/%s/%s.txt", year, day)

but received the error

Error in sprintf("http://www.weather.unh.edu/data/%s/%s.txt", year, day) : arguments cannot be recycled to the same length

I am printing these urls so I can import raw data from them in bulk. If anyone has any idea how to make this work with sprintf or another function please let me know

3 Answers 3

1

What you want is expand.grid to generate the combinations of years and days.

times <- expand.grid(days=1:365, years=2001:2004)
urls <- sprintf("http://www.weather.unh.edu/data/%s/%s.txt", times$year, times$days)
head(urls)
[1] "http://www.weather.unh.edu/data/2001/1.txt"
[2] "http://www.weather.unh.edu/data/2001/2.txt"
[3] "http://www.weather.unh.edu/data/2001/3.txt"
[4] "http://www.weather.unh.edu/data/2001/4.txt"
[5] "http://www.weather.unh.edu/data/2001/5.txt"
[6] "http://www.weather.unh.edu/data/2001/6.txt"

That said, this will encounter problems with leap years, etc; you might want to consider seq.Date instead, like

dates <- as.POSIXlt(seq.Date(as.Date("2010-01-01"), as.Date("2014-12-31"), by="day"))

And then

urls <- sprintf(".../%s/%s", dates$year + 1900, dates$yday)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a for loop:

days <- c(1:365)
years <- c(2001:2004)
urls <- c()

for (year in years) {
  for (day in days) {
    urls <- c(urls, sprintf("http://www.weather.unh.edu/data/%s/%s.txt", year, day))
  }
}

Comments

0

your running into a wall because it can't recycle the values you gave it. (365/4 is not a whole number).

Just make one string out of the two and then use sprintf

day  <- c(1:365)
year <- c(2001:2004)
day.year <- paste(rep(year,each = 365),day,sep = '/')
sprintf('http://www.weather.unh.edu/data/%s.txt',day.year)

Cheers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.