gpt4 book ai didi

r - emdist 段错误中的 emd2d 函数

转载 作者:行者123 更新时间:2023-12-02 08:42:44 25 4
gpt4 key购买 nike

我正在尝试使用 apply 将函数应用到列表,但我在执行此操作时遇到了问题。我正在尝试使用 emdist 包计算推土机距离。列表中的每个索引都有两个子索引。我想迭代计算这些子索引的推土机距离(真实列表有数千个索引)。问题是每次我尝试在测试数据集上运行代码时,Rstudio 都会崩溃。测试数据集示例:

set.seed(42) 
output1 <- list(list(matrix(0,8,11),matrix(0,8,11)), list(matrix(rnorm(80),8,10),matrix(rnorm(80),8,10)))

[[1]]
[[1]][[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0

[[1]][[2]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0

现在当我这样做时:

library(emdist)
sapply(output1,function(x) {emd2d(x[[seq_along(x)[1]]],x[[seq_along(x)[2]]]) })

Rstudio 直接崩溃了。我也尝试过:

mapply(emd2d,sapply(output1,`[`,1),sapply(output1,`[`,2)) 

但是没有效果。有任何想法吗?我在 2013 年 MacBook Air 上运行这个程序,内存为 2GB。

最佳答案

这工作正常:

> emd2d(output1[[2]][[1]],output1[[2]][[2]])
[1] -6.089909

这不会:

emd2d(output1[[1]][[1]],output1[[1]][[2]])

当您比较两个全零矩阵时,似乎emd2d()可能会讨厌它...

至少对于 OSX 上的我来说,因为这对我来说是成功的:

set.seed(666)
output2 <- list(list(matrix(5,8,11),matrix(5,8,11)),
list(matrix(rnorm(80),8,10),matrix(rnorm(80),8,10)))
sapply(output2,function(x) {emd2d(x[[1]],x[[2]]) })
#[1] 0.000000 -7.995288
# not i removed your seq_along because I don't think you really want this..

就像这样:

> set.seed(666)
> output2 <- list(list(matrix(0,8,11),matrix(5,8,11)), list(matrix(rnorm(80),8,10),matrix(rnorm(80),8,10)))
> sapply(output2,function(x) {emd2d(x[[1]],x[[2]]) })
[1] NaN -7.995288

也许您需要就此联系包创建者,同时您可以创建一个函数来检查两个矩阵是否全为零,例如

foo <- function(z){ if( sum(length(z[[1]][ z[[1]] != 0]),
length(z[[2]][ z[[2]] != 0]) ) > 0){
emd2d(z[[1]],z[[2]])
}else{
0
}
}

# i use length and subsetting, not just sum(), in case somehow
# the two matrices sum to zero because you have minus values in them

> sapply(output1, foo)
[1] 0.000000 -6.089909

关于r - emdist 段错误中的 emd2d 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892349/

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