[英]Errors attempting to applying function to data frame rows in R
我編寫了一個非常簡單的函數(效果很好),該函數在給定一組坐標的情況下返回時區:
library(XML)
findTZ <- function(lon, lat, date=Sys.Date())
{ apiurl <- sprintf("https://maps.googleapis.com/maps/api/timezone/%s?location=%s,%s×tamp=%d&sensor=%s",
"xml", lat, lon, as.numeric(as.POSIXct(date)), "false")
TZ <- xmlParse(readLines(apiurl))[["string(//time_zone_id)"]]
return(TZ)
}
findTZ(-112.86, 53.61) # example
但是,當我嘗試在數據框中的坐標列表上運行該函數時,出現錯誤: Error in file(con, "r") : invalid 'description' argument
有什么暗示我在這里錯了嗎? 看起來應該很簡單。
這是我正在測試的非常基本的數據:
DF <- data.frame(
longitude = c(-122, -112, -102),
latitude = c(54, 53, 52)
)
DF$timezone = findTZ(lon=DF$longitude, lat=DF$latitude)
謝謝您的指點!
在實現@ Floo0的答案之后,我嘗試使用另一個函數來實現相同的解決方案,該函數使用相同的位置數據來計算日出/設置時間(並且我想在本地時間返回,因此是時區函數)。
這是日出功能:
library(maptools)
SSun <- function(lon, lat, date, deg=0, dir, tzone)
{ # deg = solar depth: rise/set=0, civil=6, nautical=12, astronomical=18
# dir = direction: sunrise="dawn", sunset="dusk"
# tzone = time zone of output, NOT of location
siteX <- SpatialPoints(matrix(c(lon, lat), nrow=1), proj4string=CRS("+proj=longlat +datum=WGS84"))
dateX <- as.POSIXct(date, tz=tzone)
duskX <- crepuscule(siteX, dateX, solarDep=deg, direction=dir, POSIXct.out=TRUE)
duskX <- duskX$time # keep only date and time, discard day_frac
return(duskX)
}
SSun(-112.86, 53.61, "2016-09-25", deg=0, dir="dawn", tzone="America/Edmonton") # example
並更新了時區功能:
library(tidyverse); library(xml2)
findTZ <- function(lon, lat, date=Sys.Date()){
apiurl <- sprintf("https://maps.googleapis.com/maps/api/timezone/%s?location=%s,%s×tamp=%d&sensor=%s",
"xml", lat, lon, as.numeric(as.POSIXct(date)), "false")
read_xml(apiurl) %>% xml_find_first(".//time_zone_id") %>% xml_text
}
findTZ(-112.86, 53.61) # example
以及我用來調用這兩個函數的代碼:
DF %>% mutate(date = as.POSIXct(date),
TZ = map2_chr(longitude, latitude, findTZ),
sunrise = SSun(longitude, latitude, date, deg=0, dir="dawn", tzone=TZ))
我覺得我一定誤會了它的工作原理。 有什么見解嗎?
您可以執行以下操作(使用xml2
代替XML
因為我發現它更易於使用)
require(xml2)
findTZ <- function(lon, lat, date=Sys.Date()){
apiurl <- sprintf("https://maps.googleapis.com/maps/api/timezone/%s?location=%s,%s×tamp=%d&sensor=%s",
"xml", lat, lon, as.numeric(as.POSIXct(date)), "false")
read_xml(apiurl) %>% xml_find_first(".//time_zone_id") %>% xml_text
}
要遍歷測試數據,可以使用:
require(tidyverse)
DF %>% mutate(TZ = map2_chr(longitude, latitude, findTZ))
這給你:
longitude latitude TZ
1 -122 54 America/Vancouver
2 -112 53 America/Edmonton
3 -102 52 America/Regina
正如@Rich Scriven正確指出的那樣,您需要遍歷某個地方的數據。 在map2_chr
調用中,此循環是“隱藏的”。
考慮mapply
將每對按元素值傳遞給函數以返回向量:
DF$timezones <- mapply(findTZ, DF$longitude, DF$latitude)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.