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