我喜欢dplyr的"progress_estimated"功能,但我不知道如何在dplyr链中使用进度条。我在这里底部放置了一个带有代码的可再现示例。
我有一个相当大的数据框,像这样:
cdatetime latitude longitude
1 2013-01-11 06:40:00 CST 49.74697 -93.30951
2 2013-01-12 15:55:00 CST 49.74697 -93.30951
3 2013-01-07 20:30:00 CST 49.74697 -93.30951
我想使用库来计算每天的日出时间。
library(dplyr)
library(StreamMetabolism)
我可以在循环中使用dplyr的progress_estimated进度条,例如:
丑陋的循环(可行)
p <- progress_estimated(nrow(test))
for (i in 1:nrow(test)){
p$tick()$print()
datetime = as.POSIXct(substr(test$cdatetime[i], 1, 20), tz = "CST6CDT")
test$sunrise[i] <- sunrise.set(test$latitude[i], test$longitude[i], datetime, "CST6CDT", num.days = 1)[1,1]
}
但是我该如何将它嵌套在我的函数中,以此避免使用循环?更好的选择是:
SunriseSet <- function(dataframe, timezone){
dataframe %>%
rowwise() %>%
mutate(# calculate the date-time using the correct timezone
datetime = as.POSIXct(substr(cdatetime, 1, 20), tz = timezone),
# Get the time of sunrise and sunset on this day, at the county midpoint
sunrise = sunrise.set(latitude, longitude, datetime, timezone, num.days = 1)[1,1])
}
如何在此处添加进度条?
test2 <- SunriseSet(test, "CST6CDT")
这里是一些示例数据:
test <- data.frame(cdatetime = rep("2013-01-11 06:40:00", 300),
latitude = seq(49.74697, 50.04695, 0.001),
longitude = seq(-93.30951, -93.27960, 0.0001))