gpt4 book ai didi

r - 在 R 中的并行应用中设置矩阵行中的值

转载 作者:行者123 更新时间:2023-12-01 11:45:07 24 4
gpt4 key购买 nike

我有一个矩阵 (origmatrix),我想在其上每列执行一个函数。我想把这个函数的结果放到另一个矩阵(newmatrix)中,这一行的行号对应原矩阵中的列号。在真实数据集中,有 20000 行具有复杂的功能,所以我想使用一种应用类型,以便能够并行化项目。有没有办法让我从 apply 中获取数据到 newmatrix 中?任何帮助将不胜感激!

origmatrix = matrix(1:50, 10, 5)
colnames(origmatrix) = letters[1:5]
newmatrix = matrix(0, 5,2)
colnames(newmatrix) = c("Identifier","mean")

boertje = function (x){
newlist[which(colnames(origmatrix)==x),2]= mean(origmatrix[,x])
}
sapply(colnames(origmatrix), boertje)

最佳答案

如何使用 lapply 的多核版本,根据您的平台,它是 parallel:::mclapplymulticore:::mclapply ,然后根据结果制作数据框?当您返回多个值时,您可以制作一个数据框,如下所示:

require(parallel)
res <- mclapply( 1:ncol(origmatrix) , mc.cores = 1 , function(x){ c( mean( origmatrix[,x] ) , sd( origmatrix[,x] ) , var( origmatrix[,x] ) ) } )

# So the first element of the resulting list looks like
res[[1]]
# [1] 5.500000 3.027650 9.166667

df <- as.data.frame( res )
rownames(df) <- c("mean","sd","var")
colnames(df) <- colnames(origmatrix)
# a b c d e
# mean 5.500000 15.500000 25.500000 35.500000 45.500000
# sd 3.027650 3.027650 3.027650 3.027650 3.027650
# var 9.166667 9.166667 9.166667 9.166667 9.166667

mclapply 确实在帮助页面中出现了这个警告......

Warning
It is strongly discouraged to use these functions in GUI or embedded environments, because it leads to several processes sharing the same GUI which will likely cause chaos (and possibly crashes). Child processes should never use on-screen graphics devices.

关于r - 在 R 中的并行应用中设置矩阵行中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039138/

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