Make a general function with years from a URL

Viewed 36

Let's say I want to make a general function of a URL, for example: https://en.wikipedia.org/wiki/2020 . I want the function to act so read_url(year) generates the desired year. How do I build a general URL for this link?

The function should look like this:

read_url <- function(year){ 

...
}

And below code utilise the function to generate the link:

read_url(2015)

I assume it has to do with the rvest package.

2 Answers

We could use paste0:

read_url <- function(year){ 
  paste0("https://en.wikipedia.org/wiki/",year)
}

read_url(2015)
[1] "https://en.wikipedia.org/wiki/2015"

We can use sprintf or paste

read_url <- function(year){
   sprintf('https://en.wikipedia.org/wiki/%d', year)
}

-testing

> read_url(2015)
[1] "https://en.wikipedia.org/wiki/2015"
Related