如何在应用特定功能时加快对大型数据集的行操作

问题描述 投票:0回答:1

我正在使用R中的大数据框。我的数据框是Q,我的代码中包含类似的结构。它具有250.000行和1000列。我的目标是为每行应用一个时间序列模型,以便从每个模型中获取系数。就我而言,我将使用auto.arima程序包中的forecast函数。我尝试了两种方法来解决我的问题,接下来包括:

library(forecast)
set.seed(123)
Q <- as.data.frame(matrix(rnorm(250000*1000),nrow = 250000,ncol = 1000,byrow = T))
#Approach 1
models <- apply(Q, 1, auto.arima)
#Extract coeffs
coeffs <- lapply(models, function(x) x$coef)

#Approach 2
#Create a list and save coeff using a loop
tlist <- list(0)
for(i in 1:dim(Q)[1])
{
  models <- apply(Q[i,], 1, auto.arima)
  coeffs <- as.data.frame(lapply(models, function(x) as.data.frame(t(x$coef))))
  tlist[[i]] <- coeffs
  gc()
}

[方法1中,我使用apply()函数创建了一个列表以保存模型,因此我使用lapply()来提取系数。这种方法的问题是花了60个小时,但没有完成。

在方法2中,这是一个经典循环,目的是将函数应用于每一行,然后将结果保存在列表中。情况相同,是30个小时,但是还没有结束。

在两种情况下,任务均未完成,最终导致我的计算机崩溃。我不知道如何解决这个时间问题,因为看来我的解决方案非常慢。我的电脑有8GB内存和Windows 64位系统。我想使此操作逐行加快。如果可以直接将系数的结果添加到Q,那将是很好的选择,但是如果不可能,那么列出结果的列表将是很棒的。 Q是数据帧,但也可以是数据表。

有什么方法可以增强我的代码以获得我的结果?非常感谢您的帮助。

r dplyr data.table purrr
1个回答
1
投票
我只使用了250 x 100的矩阵-无需进行60小时的测试:)。使用2核时,时间从20秒缩短到14秒。

library(forecast) library(future.apply) set.seed(123) nr = 250L nc = 100L mat <- matrix(rnorm(nr * nc), nrow = nr, ncol = nc, byrow = TRUE) system.time(models1a <- apply(mat, 1L, auto.arima)) ## user system elapsed ## 19.84 0.02 20.04 plan("multiprocess") ## needed for future_apply to make use of multiple cores system.time(models1b <- future_apply(mat, 1L, auto.arima)) ## user system elapsed ## 0.48 0.02 14.22 ## future_lapply not needed - this is fast identical(lapply(models1a, '[[', "coef"), lapply(models1b, '[[', "coef")) ## [1] TRUE

© www.soinside.com 2019 - 2024. All rights reserved.