R代码gmapsdistance

2023-12-28

我有以下代码用于查找两个位置之间的旅行时间。我使用 vba 调用脚本,这就是命令 args 显示在顶部的原因,但出于测试目的,我只是设置变量。这一直有效到今天(没有改变任何东西),现在一旦我运行结果行,我就不断收到此错误:Error in rowXML[[dur]] : subscript out ofbounds。

有谁知道可能导致此问题的原因或这意味着什么?

Code:

#install and load necessary packages
#install.packages("gmapsdistance")
#install.packages("devtools")

args<-commandArgs(trailingOnly=T)

library("gmapsdistance")
library("devtools")
devtools::install_github("rodazuero/gmapsdistance")

#input variables from excel
orig <- args[1]
dest <- args[2]
filePath <- args[3]
api_key <- args[4]

 orig <- "London"
 dest <- "Paris"
 filePath <- "C:/Users/gabby/Documents/SeniorYear/SeniorDesign/TravelTimes/Travel_Times.csv"
 api_key <- "############################"

set.api.key(api_key)

#calls google maps and finds the time
results = gmapsdistance(origin = c(orig, dest), destination = c(dest, orig), mode = "driving", traffic_model = "best_guess", 
                        key = api_key, combinations = "pairwise", shape = "wide")

#put results in a data frame
results2 <-  data.frame(results)

#rename the column headings
names(results2) <- c("Origin","Destination", "Time", "X1","X2","Distance","X3","X4","Status")

#delete repeated origin/destination columns
results2$X1 <- NULL
results2$X2 <- NULL
results2$X3 <- NULL
results2$X4 <- NULL

#convert seconds to minutes
results2$Time <- results2$Time/60

#convert meters to miles
results2$Distance <- results2$Distance*0.000621371

#add extra column and input the current date/time for documentation
results2[,"Date"] <- NA
results2[1,"Date"] <- format(Sys.time(), "%a %b %d %X %Y %Z")

#write results2 to a csv file and save it in my folder
write.csv(results2, file = filePath)

我获得了一个 API 密钥,重现了您的问题,然后逐行浏览了底层函数的源代码。

该错误是由以下原因引起的:

data$Time[i] = as(rowXML[[dur]][1L]$value[1L]$text, 
                        "numeric")

因为对象dur仅包含以下内容:

> dur
[1] "duration"            "duration_in_traffic"

Thus rowXML[[dur]]抛出错误。我不知道该指责哪里,但 API 的变化通常比围绕它们构建的包变化得更快。

尽管如此,您仍然可以像我一样使用源代码来获取结果。只需要多几行代码就可以自己清理结果:

xmlChildren(results$row[[1L]])
$status
<status>OK</status> 

$duration
<duration>
  <value>20185</value>
  <text>5 hours 36 mins</text>
</duration> 

$distance
<distance>
  <value>459271</value>
  <text>459 km</text>
</distance> 

$duration_in_traffic
<duration_in_traffic>
  <value>20957</value>
  <text>5 hours 49 mins</text>
</duration_in_traffic> 

attr(,"class")
[1] "XMLInternalNodeList" "XMLNodeList"

根据您在评论中的要求,这里有更多关于我为得到这个所做的事情。

首先,从对该函数的调用中获取参数并从中创建对象(即,只需将每个参数作为单独的命令运行即可创建对象)。接下来,加载XML and Rcurl图书馆。另外,将您的 API 密钥放入名为的对象中key.

之后,您只需获取该函数的源代码并逐行运行它,跳过定义函数调用的部分。一路上有少量未使用的参数,您可以创建并设置它们"".

#    function (origin, destination, combinations = "all", mode, key = #get.api.key(), 
#              shape = "wide", avoid = "", departure = "now", dep_date = "", 
#              dep_time = "", traffic_model = "best_guess", arrival = "", 
#              arr_date = "", arr_time = "") # don't run this
  if (!(mode %in% c("driving", "walking", "bicycling", "transit"))) {
    stop("Mode of transportation not recognized. Mode should be one of ", 
         "'bicycling', 'transit', 'driving', 'walking' ")

  if (!(combinations %in% c("all", "pairwise"))) {
    stop("Combinations between origin and destination not recognized. Combinations should be one of ", 
         "'all', 'pairwise' ")
  }
  if (!(avoid %in% c("", "tolls", "highways", "ferries", "indoor"))) {
    stop("Avoid parameters not recognized. Avoid should be one of ", 
         "'tolls', 'highways', 'ferries', 'indoor' ")
  }
  if (!(traffic_model %in% c("best_guess", "pessimistic", "optimistic"))) {
    stop("Traffic model not recognized. Traffic model should be one of ", 
         "'best_guess', 'pessimistic', 'optimistic'")
  }
  seconds = "now"
  seconds_arrival = ""
  UTCtime = strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%OS", 
                     tz = "GMT")
  min_secs = round(as.numeric(difftime(as.POSIXlt(Sys.time(), 
                                                  "GMT"), UTCtime, units = "secs")))
  if (dep_date != "" && dep_time != "") {
    depart = strptime(paste(dep_date, dep_time), "%Y-%m-%d %H:%M:%OS", 
                      tz = "GMT")
    seconds = round(as.numeric(difftime(depart, UTCtime, 
                                        units = "secs")))
  }
  if (departure != "now") {
    seconds = departure
  }
  if (departure != "now" && departure < min_secs) {
    stop("The departure time has to be some time in the future!")
  }
  if (dep_date != "" && dep_time == "") {
    stop("You should also specify a departure time in the format HH:MM:SS UTC")
  }
  if (dep_date == "" && dep_time != "") {
    stop("You should also specify a departure date in the format YYYY-MM-DD UTC")
  }
  if (dep_date != "" && dep_time != "" && seconds < min_secs) {
    stop("The departure time has to be some time in the future!")
  }
  if (arr_date != "" && arr_time != "") {
    arriv = strptime(paste(arr_date, arr_time), "%Y-%m-%d %H:%M:%OS", 
                     tz = "GMT")
    seconds_arrival = round(as.numeric(difftime(arriv, UTCtime, 
                                                units = "secs")))
  }
  if (arrival != "") {
    seconds_arrival = arrival
  }
  if (arrival != "" && arrival < min_secs) {
    stop("The arrival time has to be some time in the future!")
  }
  if (arr_date != "" && arr_time == "") {
    stop("You should also specify an arrival time in the format HH:MM:SS UTC")
  }
  if (arr_date == "" && arr_time != "") {
    stop("You should also specify an arrival date in the format YYYY-MM-DD UTC")
  }
  if (arr_date != "" && arr_time != "" && seconds_arrival < 
      min_secs) {
    stop("The arrival time has to be some time in the future!")
  }
  if ((dep_date != "" || dep_time != "" || departure != "now") && 
      (arr_date != "" || arr_time != "" || arrival != "")) {
    stop("Cannot input departure and arrival times. Only one can be used at a time. ")
  }
  if (combinations == "pairwise" && length(origin) != length(destination)) {
    stop("Size of origin and destination vectors must be the same when using the option: combinations == 'pairwise'")
  }
  if (combinations == "all") {
    data = expand.grid(or = origin, de = destination)
  }
  else if (combinations == "pairwise") {
    data = data.frame(or = origin, de = destination)
  }
  n = dim(data)
  n = n[1]
  data$Time = NA
  data$Distance = NA
  data$status = "OK"
  avoidmsg = ""
  if (avoid != "") {
    avoidmsg = paste0("&avoid=", avoid)
  }











  for (i in 1:1:n) {
    url = paste0("maps.googleapis.com/maps/api/distancematrix/xml?origins=", 
                 data$or[i], "&destinations=", data$de[i], "&mode=", 
                 mode, "&sensor=", "false", "&units=metric", "&departure_time=", 
                 seconds, "&traffic_model=", traffic_model, avoidmsg)
    if (!is.null(key)) {
      key = gsub(" ", "", key)
      url = paste0("https://", url, "&key=", key)
    }
    else {
      url = paste0("http://", url)
    }
    webpageXML = xmlParse(getURL(url))
    results = xmlChildren(xmlRoot(webpageXML))
    request.status = as(unlist(results$status[[1]]), "character")
    if (!is.null(results$error_message)) {
      stop(paste(c("Google API returned an error: ", xmlValue(results$error_message)), 
                 sep = ""))
    }
    if (request.status == "REQUEST_DENIED") {
      set.api.key(NULL)
      data$status[i] = "REQUEST_DENIED"
    }
    rowXML = xmlChildren(results$row[[1L]])
    Status = as(rowXML$status[1]$text, "character")
    if (Status == "ZERO_RESULTS") {
      data$status[i] = "ROUTE_NOT_FOUND"
    }
    if (Status == "NOT_FOUND") {
      data$status[i] = "PLACE_NOT_FOUND"
    }
    if (Status == "OVER_QUERY_LIMIT") {
      stop("You have exceeded your allocation of API requests for today.")
    }
    if (data$status[i] == "OK") {
      data$Distance[i] = as(rowXML$distance[1]$value[1]$text, 
                            "numeric")
      dur = grep("duration", names(rowXML), value = TRUE)
      data$Time[i] = as(rowXML[[dur]][1L]$value[1L]$text, 
                        "numeric")
    }
  }


  datadist = data[c("or", "de", "Distance")]
  datatime = data[c("or", "de", "Time")]
  datastat = data[c("or", "de", "status")]
  if (n > 1) {
    if (shape == "wide" && combinations == "all") {
      Distance = reshape(datadist, timevar = "de", idvar = c("or"), 
                         direction = "wide")
      Time = reshape(datatime, timevar = "de", idvar = c("or"), 
                     direction = "wide")
      Stat = reshape(datastat, timevar = "de", idvar = c("or"), 
                     direction = "wide")
    }
    else {
      Distance = datadist
      Time = datatime
      Stat = datastat
    }
  }
  else {
    Distance = data$Distance[i]
    Time = data$Time[i]
    Stat = data$status[i]
  }
  output = list(Time = Time, Distance = Distance, Status = Stat)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R代码gmapsdistance 的相关文章

  • 通过 rpy 将 SPSS 文件(.sav)导入 pandas 时如何保留标签?

    我正在寻找使用 SPSS 文件 sav pandas 在没有 SPSS 程序的情况下 典型文件转换为 csv 后的样子如下 在调查前两行的含义时 我不知道 SPSS 似乎第一行包含Labels 而第二行包含VarNames 当我将文件带入
  • 矩阵中两个字符串的最大 nchar

    我想找到更好的方法来找到我正在相互比较的两个字符串的更大的 nchar 假设我有字符串句子匹配data frame 和我需要创建一个 max nchar string1 nchar string2 矩阵 但没有 for 循环 这是非常慢的方
  • 准备编程竞赛的缩写和函数[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 根据条件计算平均值

    下面是我的数据框 Row ID A B 1 0 0 2 0 0 3 0 0 4 0 1 5 0 1 6 0 1 7 62 75 0 8 100 0 9 100 0 10 100 1 11 100 1 12 100 1 13 100 1 14
  • r testthat 和 covr 在非包库中使用

    我希望能够使用testthat and covr在一个项目中not一个 r 包 事实上不使用任何第三方服务 只是普通的旧 r 源文件的集合 我正在努力找出这是否可行 如果可以 则已设置有关如何设置的说明 我发现假设你正在编写一个 r 包 我
  • 使用 ggplot 未完全填充等值线图

    我正在尝试使用以下方法绘制我的第一个填充等高线图ggplot 根据我的数据 我期待类似的结果 但我的结果是 a lt c 1 1 1 1 1 3 1 2 2 2 2 2 2 5 2 1 3 3 3 3 1 3 2 b lt c rep c
  • 如何使用 ggplot2 绘制 NA 间隙

    在 R 的基本绘图中 如果数据系列 ggplot2 中存在 NA 则会绘制间隙 举个例子看看 df data frame x c 1 10 y c 1 10 df 5 7 NA plot df type l 但是 ggplot2 删除了缺失
  • 如何在 rmarkdown 中显示带有 results='asis' 的格式化 R 输出

    当使用 results asis 时 有没有办法在 rmarkdown knitr 中显示格式化程序 R 输出 一个例子是以下函数 myfun lt function cat hello n cat c one 1 two 2 然后 该块将
  • R.scale() 和 sklearn.preprocessing.scale() 之间的区别

    我目前正在将数据分析从 R 转移到 Python 当在 R 中缩放数据集时 我将使用 R scale 根据我的理解 它将执行以下操作 x mean x sd x 为了替换该函数 我尝试使用 sklearn preprocessing sca
  • 用于带有嵌套子图的图的 r 包? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在寻找一个用于图形 网络的 r 包 它可以处理嵌套子图 Graphviz 做到了这一点 但只提供可
  • 如何使用 RODBC 将数据帧保存到数据库生成的主键表

    我想使用 R 脚本将数据框输入到数据库中的现有表中 并且希望数据库中的表具有顺序主键 我的问题是 RODBC 似乎不允许主键约束 这是创建我想要的表的 SQL CREATE TABLE dbo results ID INT IDENTITY
  • 读取并绘制从大文件中读取的数据

    我们有相当大的文件 大约为 1 1 5 GB 主要是日志文件 其中包含易于解析为 csv 的原始数据 随后应该将其绘制成图表以生成一组图形图像 目前 我们正在使用 bash 脚本将原始数据转换为 csv 文件 其中仅包含需要绘制图表的数字
  • 使用 igraph 将边缘属性显示为标签

    我在 R 中使用 igraph 进行网络分析 我想在图中的每条线上显示边缘属性 下面是一个例子 df lt data frame a c 0 1 2 3 4 b c 3 4 5 6 7 nod lt data frame node c 0
  • 如何在R中使用OpenNLP获取POS标签?

    这是 R 代码 library NLP library openNLP tagPOS lt function x s lt as String x word token annotator lt Maxent Word Token Anno
  • R中的不定积分

    我正在计算方程的不定积分 我将加速度计的数据通过可视化 C 程序输入到 R 中 然后就可以很简单地得出一个方程来表示加速度曲线 这一切都很好 但是我还需要计算撞击速度 根据我在高中时代的理解 我的加速度曲线的不定积分将产生速度方程 我知道执
  • Openxlsx 多次验证损坏输出文件

    我正在尝试添加多个验证并将公式添加到 Excel 文件 这是我使用的代码 library openxlsx fileTemplate lt New01 xlsx wbTemplate lt loadWorkbook fileTemplate
  • 在 R 中使用 gsub 删除尾随空格[重复]

    这个问题在这里已经有答案了 有没有人有一个技巧可以用 gsub 删除变量上的尾随空格 以下是我的数据示例 正如您所看到的 我在变量中同时包含尾随空格和嵌入空格 county lt c mississippi mississippi cany
  • 使用 RMySQL 会干扰 RPostgreSQL

    我有一个 R 脚本 我想从 MySQL 数据库中提取一些数据 然后从 PostgreSQL 数据库中提取一些数据 但是 从 RMySQL 加载 MySQL 驱动程序会阻止我从以下位置加载 PostgreSQL 驱动程序 PostgreSQL
  • Rstudio 命令历史记录

    这些天我经常使用 Rstudio 但最近注意到我的命令不再存储在历史记录中 我不知道这是从什么时候开始的 但可能是在安装最新版本时发生的 关于问题可能是什么的任何想法吗 Thanks 这是我们在 v0 93 73 中引入并在 v0 93 7
  • ggplot堆叠条 - 隐藏标签但保留标签位置

    我在 ggplot 中有一个堆积条形图 其中 geom text 标签位于每个条形的中心 我想隐藏小条上的标签 以便图表看起来不会过于拥挤 我可以使用下面的代码来完成此操作 但它会弄乱标签的位置 正如您在下面的链接图片中看到的那样 它们不再

随机推荐

  • 如果 ASP.NET 破坏了 DIV 的 ID,如何从 javascript 访问该 DIV?

    我有一个包含 div 元素的网页 在页面上 有 javascript 来引用 div document getElementById divId 在另一位开发人员重新设计该页面以使用 ASP 母版页之前 该方法一直运行良好 Now docu
  • 流复制和逻辑复制的区别

    有人能告诉我更多关于 PostgreSQL 中物理复制和逻辑复制之间的区别吗 TL DR 逻辑复制发送逐行更改 物理复制发送磁盘块更改 逻辑复制对于某些任务更好 而物理复制对于其他任务更好 请注意 在 PostgreSQL 12 更新时的当
  • Rails 购物车 - 未添加到当前订单

    这里是 Rails 菜鸟 我正在构建一个基本的购物车 它之前运行良好 在不更改任何代码的情况下 我 git reset hard 到我以前的提交 它正在工作 它就崩溃了 这是细分 Github 仓库 https github com chr
  • 编译引用的dll

    使用VS2005和VB NET 我有一个项目 它是我创建的数据存储的 API 编译时创建api dll 我在同一解决方案中有第二个项目 它有一个对 API 项目的项目引用 编译时将创建wrapper dll 这基本上是特定于应用程序的 AP
  • 显示对象而不是字符串

    在这里 我附上了我的问题的快照和代码 它只向我显示作为对象的内容 但完美地显示组名 这个问题的快照在下面的链接中给出 只需浏览这张图片 http imageupload org d 4DA941521 快照 gt 我想要特定组名称的子数据
  • 使用 kafka 进行 Spark 结构化流处理只会导致一批(Pyspark)

    我有以下代码 我想知道为什么它只生成一批 df spark readStream format kafka option kafka bootstrap servers IP option subscribe Topic option st
  • 如何设计一个数据库来存储属性,通过同义词选择属性

    我正在为房地产应用程序设计一个数据库 事实证明 它比我预期的更复杂 也许我把事情复杂化了 这些问题本质上是由于以下因素的存在造成的 同义词 例如 术语 公寓 公寓和顶层公寓本质上都指的是同一类型的房产 属性 不同的属性类型有不同的属性 例如
  • 批处理:连接变量和字符串以形成输出路径

    我有一个批处理文件 用户在其中输入文件的路径 然后从该路径中提取文件名 我使用该文件名创建一个同名的文件夹 在该文件夹中 我想创建一个 log txt 文件 我在批处理文件中调用的进程可以将其日志消息写入其中 这是代码 set p path
  • 将数据框与从应用函数创建的另一个数据框合并?

    我有一个数据框 df 工资数据 State Annual Salary New York 132826 New Hampshire 128704 California 127388 Vermont 121599 Idaho 120011 还
  • 在 C# 中访问已释放的闭包?

    我正在调查 Microsoft 企业库 数据应用程序块 示例 sln 他们有一个异步读取数据的示例 IAsync 虽然新版本 6 也支持async 但是雷沙珀 或视觉工作室 没关系 向我展示 访问已处理的闭包 首先我将显示图像 这样会更清晰
  • 从一个位置移动到另一个位置后 UIButton 框架发生变化

    我有 1UIButton in StoryBoard就像下面的屏幕一样 我移动UIButton按照此从一个位置到另一个位置Answer https stackoverflow com questions 45392104 drag uibu
  • NetBeans 远程连接

    我正在尝试设置 netBeans 远程项目 但遇到了很多麻烦 我已经从远程服务器启动了一个 PHP 应用程序 在最后一个确认步骤中它向我抛出了错误 没有可供下载的文件 尝试在远程配置中检查被动模式 在日志输出中 它失败了 gt 215 UN
  • Facelets ui:remove 标签的实际意义

    我想了解基本机制
  • Maven 原型不使用属性来创建模块名称

    我创建了一个原型 您可以在其中设置 moduleName 或期望 使用 必需的属性 moduleName 这里是原型元数据 xml 减少 我也尝试过类似的结果
  • 数据库中的闰秒处理

    As The Unix time number is zero at the Unix epoch and increases by exactly 86400 per day since the epoch So it cannot re
  • DTD 是否已被弃用?

    In XML 模式和 DTD 有什么区别 https stackoverflow com questions 1544200 what is difference between xml schema and dtd 两个回答者表示 DTD
  • Angular Js HTML5 模式不起作用 [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我正在尝试将 HTML5 模式添加到我的 Angular 应用程序中以删除 符号 问题是它根本行不通 我的整个 ng view 将
  • Maven:在战争构建的资源文件夹中包含文件夹

    我在 src main resource 中有一个名为 extra jars 的文件夹 但如何将它们包含在构建中 我希望它们与其余的 jar 一起放入 lib 文件夹中 我尝试将它们包括在内 但这没有用 对于不是由 Maven 存储库分发的
  • 消息:配置的数据库连接是持久的。正在中止

    Codeigniter 2 到 3 版本升级后 出现此错误 为什么会这样呢 遇到未捕获的异常 类型 异常 消息 配置的数据库连接是持久的 正在流产 文件名 var www vhosts xxx com app system librarie
  • R代码gmapsdistance

    我有以下代码用于查找两个位置之间的旅行时间 我使用 vba 调用脚本 这就是命令 args 显示在顶部的原因 但出于测试目的 我只是设置变量 这一直有效到今天 没有改变任何东西 现在一旦我运行结果行 我就不断收到此错误 Error in r