I am using map
function from purrr
library to apply segmented
function (from segmented
library) as follows:
library(purrr)
library(dplyr)
library(segmented)
# Data frame is nested to create list column
by_veh28_101 <- df101 %>%
filter(LCType=="CFonly", Lane %in% c(1,2,3)) %>%
group_by(Vehicle.ID2) %>%
nest() %>%
ungroup()
# Functions:
segf2 <- function(df){
try(segmented(lm(svel ~ Time, data=df), seg.Z = ~Time,
psi = list(Time = df$Time[which(df$dssvel != 0)]),
control = seg.control(seed=2)),
silent=TRUE)
}
segf2p <- function(df){
try(segmented(lm(PrecVehVel ~ Time, data=df), seg.Z = ~Time,
psi = list(Time = df$Time[which(df$dspsvel != 0)]),
control = seg.control(seed=2)),
silent=TRUE)
}
# map function:
models8_101 <- by_veh28_101 %>%
mutate(segs = map(data, segf2),
segsp = map(data, segf2p))
The object by_veh28_101
contains 2457 tibbles
. And the last step, where map
function is used, takes 16 minutes to complete. Is there any way to make this faster?
purrr
that's slow here, it'ssegmented
. You're running thousands of models, which takes a while. Profile your code to see exactly what the bottlenecks are. – Olgaolguin