替换R函数中的部分url

时间:2016-02-10 07:13:31

标签: r function url

我想在R中创建一个函数,它将从任何wunderground.com csv中读取数据。我在此过程中的第一步是编写用URL替换所需位置和日期的代码。调用每月汇总csv文件的URL格式如下:wunderground.com/history/airport/KISW/2016/2/1/MonthlyHistory.html?format=1。

这是我迄今为止的尝试:

my_function <- function(location, month) {
    url <- paste0("wunderground.com/history/airport/",'location', "/2016/", "month", "/1/MonthlyHistory.html?format=1")
    print(url)

}

当我调用此函数时,例如:

my_function(location = KMSN, month = 2)

我明白了:

[1] wunderground.com/history/airport/location/2016/month/1/MonthlyHistory.html?format=1, 

但我希望它会:

wunderground.com/history/airport/KMSN/2016/2/1/MonthlyHistory.html?format=1

我也尝试在函数中使用gsub:

my_function1 <- function(location, month) {
    url <- "wunderground.com/history/airport/code/2016/month/1/MonthlyHistory.html?format=1"
    urll <- gsub("code", "location", url)
    print(url)
}

但我也没有成功。我明白了:

[1] wunderground.com/history/airport/code/2016/month/1/MonthlyHistory.html?format=1

我做错了什么?感谢您的投入。

2 个答案:

答案 0 :(得分:0)

我们可以修改该功能并使用sprintf

my_function <- function(location, month) {
   url <- sprintf(paste0("wunderground.com/history/airport/",location, "/2016/%s/1/MonthlyHistory.html?format=1"), month)
   print(url)
 }

 my_function("KMSL", 2)
 #[1] "wunderground.com/history/airport/KMSL/2016/2/1/MonthlyHistory.html?format=1"

或者@Tensibai建议

 my_function <- function(location, month) {
    sprintf("wunderground.com/history/airport/%s/2016/%s/1/MonthlyHistory.html?format=1", location, month)
    }
 my_function("KMSL",2)
 #[1] "wunderground.com/history/airport/KMSL/2016/2/1/MonthlyHistory.html?format=1"

答案 1 :(得分:0)

my_function1 <- function(location, month) {
    url <- "wunderground.com/history/airport/code/2016/month/1/MonthlyHistory.html?format=1"
    urll <- gsub("code", "location", url)
    print(url)
}

注意:您的上述功能正常。但在最后一个print语句中将'url'替换为'urll'。还需要为'月'添加'gsub'。