在R中的mutate语句中调用API

约翰尼·托马斯(Johnny Thomas)

我正在尝试使用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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章