r - 在 R 中的 mutate 语句中调用 API

标签 r api tidyverse dplyr

我正在尝试使用 API 确定给定日期的日出时间

所以我有一个像这样的数据框

        Date
1 2018-01-03
2 2018-01-03
3 2018-01-04
4 2018-01-08
5 2018-01-09

虽然我可以在没有粘贴语句的情况下让它工作,但当我将它放入 mutate 时,它​​不起作用并返回错误:

dates <- structure(list(Date = c("2018-01-03", "2018-01-03", "2018-01-04", 
"2018-01-08", "2018-01-09")), row.names = c(NA, 5L), class = "data.frame")


dates %>% 
  mutate(sunrise = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=", Date))$content))$results[1])
           )

ERROR:
Error: Problem with `mutate()` input `sunrise`.
x length(url) == 1 is not TRUE
i Input `sunrise` is `as.character(...)`.

这里的目标是我希望每天都有一个新的日出列。如果我更改 Paste0 字段并给它一个精确的字符串,它会完美地工作,但不会在 mutate 中,我不明白为什么......

最佳答案

这可以通过dplyr::rowwise来实现

library(dplyr)
library(httr)
library(jsonlite)

dates <- structure(list(Date = c("2018-01-03", "2018-01-03", "2018-01-04", 
                                 "2018-01-08", "2018-01-09")), row.names = c(NA, 5L), class = "data.frame")

dates %>% 
  rowwise() %>% 
  mutate(sunrise = as.character(fromJSON(rawToChar(GET(paste0("https://api.sunrise-sunset.org/json?lat=40.730610&lng=-73.935242&date=",Date))$content))$results[1]))
#> # A tibble: 5 x 2
#> # Rowwise: 
#>   Date       sunrise    
#>   <chr>      <chr>      
#> 1 2018-01-03 12:19:53 PM
#> 2 2018-01-03 12:19:53 PM
#> 3 2018-01-04 12:19:52 PM
#> 4 2018-01-08 12:19:27 PM
#> 5 2018-01-09 12:19:15 PM

关于r - 在 R 中的 mutate 语句中调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62882557/

相关文章:

在 Bookdown 中渲染附录图编号

r - 使用 tidyverse 在组内将长转为宽

R : extracting words from a string 中的正则表达式

r - GGplot Barplot 不接受 Y 值?

javascript - TypeError : this. state.student.map 不是一个函数

java - 以编程方式访问 Java 文档

javascript - JS脚本中的执行顺序

r - 使用tidyverse的R中多列的加权和

r - 向量元素到数据框的不同列

R:如何从两个不同的列获取百分比变化