使用循环将 gmapsdistance 应用于 R 中的列表

Using a loop to apply gmapsdistance to a list in R

我正在尝试使用 R 中的 gmapsdistance 包通过 public 邮政编码列表(起点)和单个目的地邮政编码之间的传输来计算行程时间。

单个查询的输出是:

  $Time
[1] 5352

$Distance
[1] 34289

$Status
[1] "OK"

我实际上有 2.5k 个邮政编码要使用,但在我对其进行故障排除时,我将迭代次数设置为 10。london1 是一个数据框,包含一个列,2500 行中有 2500 个邮政编码。

这是我目前的尝试;

 results <- for(i in 1:10) {
gmapsdistance::set.api.key("xxxxxx")
gmapsdistance::gmapsdistance(origin = "london1[i]"
                              destination = "WC1E 6BT"
                              mode = "transit"
                              dep_date = "2017-04-18"
                              dep_time = "09:00:00")}

当我 运行 这个循环时,我得到

results <- for(i in 1:10) { + gmapsdistance::set.api.key("AIzaSyDFebeOppqSyUGSut_eGs8JcjdsgPBo8zk") + gmapsdistance::gmapsdistance(origin = "london1[i]" + destination = "WC1E 6BT" Error: unexpected symbol in: " gmapsdistance::gmapsdistance(origin = "london1[i]" destination" mode = "transit" dep_date = "2017-04-18" dep_time = "09:00:00")} Error: unexpected ')' in " dep_time = "09:00:00")"

我的问题是:

1)我该如何解决这个问题?

2) 我需要如何对其进行格式化,以便输出是包含起点邮政编码和旅程时间的数据框或矩阵

谢谢

这里发生了一些事情:

  • "london[i]" 需要 london[i, 1]
  • 你需要用逗号分隔你的参数,
  • 我在使用时遇到错误,例如 "WC1E 6BT",我发现有必要将 space 替换为破折号,例如 "WC1E-6BT"
  • 循环需要显式地为 results
  • 的元素赋值

所以你的代码看起来像这样:

library(gmapsdistance)
## some example data
london1 <- data.frame(postCode = c('WC1E-7HJ', 'WC1E-6HX', 'WC1E-7HY'))

## make an empty list to be filled in
results <- vector('list', 3)
for(i in 1:3) {
    set.api.key("xxxxxx")
    ## fill in your results list
    results[[i]] <- gmapsdistance(origin = london1[i, 1],
                                  destination = "WC1E-6BT",
                                  mode = "transit",
                                  dep_date = "2017-04-18",
                                  dep_time = "09:00:00")
}

事实证明,当使用 gmapsdistance(参见帮助文档)时,您不需要循环——而且可能不应该——而且来自多个输入的输出也有助于快速格式化你的输出变成 data.frame:

set.api.key("xxxxxx")
temp1 <- gmapsdistance(origin = london1[, 1],
              destination = "WC1E-6BT",
              mode = "transit",
              dep_date = "2017-04-18",
              dep_time = "09:00:00", 
              combinations = "all")

上面的 returns 是 data.frame 个对象的列表,TimeDistanceStatus 各一个。然后你可以很容易地把它们变成一个 data.frame 包含你可能想要的一切:

res <- data.frame(origin = london1[, 1],
                  desination = 'WC1E-6BT',
                  do.call(data.frame, lapply(temp1, function(x) x[, 2])))

lapply(temp1, function(x) x[, 2]) 从列表中的每个 data.frame 中提取所需的列,然后 do.call 将它们重新组合为新的 data.frame 对象中的列。