gpt4 book ai didi

r - 将函数应用于DataFrame中的每个单元格或R中的多线程矩阵

转载 作者:行者123 更新时间:2023-12-03 12:59:25 24 4
gpt4 key购买 nike

是否可以在R中以多线程方式将函数应用于DataFrame/矩阵中的每个单元格?

我知道apply(),但它似乎不允许本地进行多线程处理:

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

最佳答案

可能有几种方法可以做到这一点,但是我一直发现对列表对象运行并行操作最简单。如果将输入矩阵转换为列表,则可以使用parallel::parLapply来应用该函数,如下所示:

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

这应该跨平台工作。
> 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

关于r - 将函数应用于DataFrame中的每个单元格或R中的多线程矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45154424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com