2017-07-17 49 views
2

是否可以將函數應用於DataFrame/matrix中的每個單元格多線程將函數應用於DataFrame中的每個單元或多線程中的矩陣R

我知道申請(),但它似乎並沒有讓本機的多線程:

x <- cbind(x1 = 3, x2 = c(4:1, 2:5)) 

cave <- function(x, c1, c2) { 
    a = 1000 
    for (i in 1:100) { # Useless busy work 
    b=matrix(runif(a*a), nrow = a, ncol=a) 
    } 
    c1 + c2 * x  
} 

apply(x, 1, cave, c1 = 3, c2 = 4) 

回報:

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] 
x1 15 15 15 15 15 15 15 15 
x2 19 15 11 7 11 15 19 23 

相反,我想用一個以上的核心以執行操作,因爲應用的功能可能很複雜。例如,可以使用apply a function to each cell in DataFrame multithreadedly in pandas

+1

你是否檢查過並行包中的mcmapply? –

+2

請注意,mcmapply不能在Windows系統中工作... –

回答

2

可能有幾種方法可以做到這一點,但我總是發現在列表對象上運行並行操作最容易。

## convert the input object to a list 
x.list <- split(t(x), rep(1:nrow(x), each = ncol(x))) 

## parallelize the operation over e.g. 2 cores 
cl <- parallel::makeCluster(2) 
out <- parallel::parLapply(cl, x.list, cave, c1 = 3, c2 = 4) 
parallel::stopCluster(cl) 

## transform the output list back to a matrix 
out <- t(matrix(unlist(out, use.names = FALSE), nrow = ncol(x))) 
colnames(out) <- colnames(x) 

這應該跨平臺工作:如果您在輸入矩陣轉換到一個列表,該功能可以使用並行:: parLapply如下應用。

> x 
    x1 x2 
[1,] 3 4 
[2,] 3 3 
[3,] 3 2 
[4,] 3 1 
[5,] 3 2 
[6,] 3 3 
[7,] 3 4 
[8,] 3 5 
> out 
    x1 x2 
[1,] 15 19 
[2,] 15 15 
[3,] 15 11 
[4,] 15 7 
[5,] 15 11 
[6,] 15 15 
[7,] 15 19 
[8,] 15 23 
相關問題