尝试将函数应用于R中的数据帧行时出错
我编写了一个非常简单的函数(运行良好),它返回给定坐标集的时区:尝试将函数应用于R中的数据帧行时出错,r,function,vectorization,R,Function,Vectorization,我编写了一个非常简单的函数(运行良好),它返回给定坐标集的时区: 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, l
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
谢谢你的指点
编辑/添加
在实现@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
我觉得我一定是误解了这是怎么回事。有什么见解吗?您可以执行以下操作(使用xml2
而不是XML
,因为我发现它更易于使用)
这给了你:
longitude latitude TZ
1 -122 54 America/Vancouver
2 -112 53 America/Edmonton
3 -102 52 America/Regina
正如@Rich Scriven正确指出的,您需要在某个地方循环数据。此循环在
map2\u chr
调用中“隐藏”。考虑mapply
将每对元素值传递到函数中以返回向量:
DF$timezones <- mapply(findTZ, DF$longitude, DF$latitude)
DF$时区
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
DF$timezones <- mapply(findTZ, DF$longitude, DF$latitude)