我试图使用dplyr来计算一组lon/lat/time戳坐标的日出时间,使用maptools中的sunriset函数。这里是一个可重复的例子。
library(maptools)
library(dplyr)
pts <- tbl_df(data.frame(
lon=c(12.08752,12.08748,12.08754,12.08760,12.08746,12.08748),
lat=c(52.11760,52.11760,52.11747,52.11755,52.11778,52.11753),
timestamp=as.POSIXct(
c("2011-08-12 02:00:56 UTC","2011-08-12 02:20:22 UTC",
"2011-08-12 02:40:15 UTC","2011-08-12 03:00:29 UTC",
"2011-08-12 03:20:26 UTC","2011-08-12 03:40:30 UTC"))
))
pts %>% mutate(sunrise=sunriset(as.matrix(lon,lat),
timestamp,POSIXct.out=T,
direction='sunrise')$time)当我运行这段代码时,我会得到错误。
“错误:无效下标类型‘闭包’”
我猜这意味着我没有将变量正确地传递到sunriset中。
如果我不使用dplyr,这个方法就能工作。
pts$sunrise<-sunriset(as.matrix(select(pts,lon,lat)),
pts$timestamp, POSIXct.out=T,
direction='sunrise')$time但是,我有很多行(大约6,500万行),即使其中的一小部分,上面的方法也很慢。我希望dplyr会更快。如果有人对最快的方法有其他的建议,我很想听听。
发布于 2015-09-27 16:06:27
sunr <- function(lon, lat, ts, dir='sunrise') {
# can also do matrix(c(pts$lon, pts$lat), ncol=2, byrow=TRUE) vs
# as.matrix(data.frame…
sunriset(as.matrix(data.frame(lon, lat)), ts, POSIXct.out=TRUE, direction=dir)$time
}
pts %>% mutate(sunrise = sunr(lon, lat, timestamp))是处理它的一种方法(并且有更干净的mutate管道的副作用),但是我不知道为什么你认为它会更快。不管是哪种方式,瓶颈都是(很可能)为调用sunriset创建矩阵,无论是哪种方式都会发生这种情况。
maptools源代码非常容易通过,并且具有一个非导出函数maptools:::.sunrisetUTC(),它可以:
".sunrisetUTC" <- function(jd, lon, lat, direction=c("sunrise", "sunset")) {
## Value: Numeric, UTC time of sunrise or sunset, in minutes from zero
## Z.
## --------------------------------------------------------------------
## Arguments: jd=julian day (real);
## lon=lat=longitude and latitude, respectively, of the observer in
## degrees;
## sunrise=logical indicating whether sunrise or sunset UTC should be
## returned.您可以尝试在julian day、lon、lat和direction中传递给它与导出的函数比较,以避免数据复制。但是,如果性能非常关键,我会使用Rcpp编写一个基于这的内联的、矢量化的C/C++函数。
https://stackoverflow.com/questions/32809555
复制相似问题