Home > Software engineering >  Make a general function with years from a URL
Make a general function with years from a URL

Time:07-31

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.

CodePudding user response:

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"

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related