r - 如何让purrr map 函数运行得更快?

标签 r dplyr purrr

我正在使用 purrr 库中的 map 函数来应用 segmented 函数(来自 segmented 库),如下所示:

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))  

对象by_veh28_101包含2457个tibbles。最后一步使用 map 函数,需要 16 分钟才能完成。有什么办法可以让它更快吗?

最佳答案

您可以使用函数future_map代替map

该函数来自 furrr 包,是 map 系列的并行选项。这是 README 的链接包的。

因为您的代码问题不可重现,所以我无法在 mapfuture_map 函数之间准备基准。

使用 future_map 函数的代码如下:

library(tidyverse)
library(segmented)
library(furrr)


# Data frame stuff....

# Your functions....

# future_map function

# this distribute over the different cores of your computer
# You set a "plan" for how the code should run. The easiest is `multiprocess`
# On Mac this picks plan(multicore) and on Windows this picks plan(multisession)

plan(strategy = multiprocess)

models8_101 <- by_veh28_101 %>% 
  mutate(segs = future_map(data, segf2),
         segsp = future_map(data, segf2p)) 

关于r - 如何让purrr map 函数运行得更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005938/

相关文章:

r - 垂直对齐 ggplot2 绘图

r - if() 和 ifelse() 函数之间的区别

r - 如何确定是否在特定列中找到某个值?

r - 为什么 "//*"是我使用 XML 包在 R 中解析此 XML 时唯一有效的 xPath 查询?

r - 如何使用 dplyr 管道重命名数据框中指定行之后的所有列

r - 为什么 data.tables mutate(row_number()) 失败?

行式迭代,如 apply with purrr

r - Purrr 和 R 中的几个多元回归

r - 将 data.frame 列名称传递给使用 purrr::map 的函数

r - R 中计算线性回归的异方差稳健置信区间的函数