嵌套的for循环适用于矩阵列表-输出不一致

时间:2018-09-03 15:45:10

标签: r for-loop nested apply lapply

我对嵌套循环进行了计算,然后尝试将其转换为lapply,但显示的结果不同,您知道为什么吗?这是我的代码:

#list
l <- list()
l[[1]] <- matrix(c(4, 3, 20, 10), ncol=2)
l[[2]] <- matrix(c(3, 3, 40, 12), ncol=2)
l[[3]] <- matrix(c(2, 3, 60, 10), ncol=2)
#loop
##index
s <- 1:length(l)
#for loop
zzz <- list()
for (i in s){
zzz[[i]] <- apply(X = l[[i]], MARGIN = 1, 
                FUN = function(x) spDistsN1(l[[i]], x, longlat = T))
zzz
}
#lapply loop
yyy <- lapply(s, function(x){
apply(X = l[[i]], MARGIN = 1, 
    FUN = function(x) spDistsN1(l[[i]], x, longlat = T))
})

它们的输出不相同,为什么?

identical(zzz,yyy)
[1] FALSE    

1 个答案:

答案 0 :(得分:1)

我们可以将代码更改为

library(sp)
yyy <- lapply(s, function(i) apply(l[[i]], 1, FUN= function(x) 
             spDistsN1(l[[i]], x, longlat = TRUE)))
identical(zzz, yyy)
#[1] TRUE

在OP的代码中,两个函数中使用的匿名函数调用为x,因此在spDistsN1中,x来自整个matrix,而不是整个SELECT (SELECT STRING_AGG(DISTINCT s, ', ') FROM UNNEST(SPLIT(Customer1, ', ')) AS s) AS Customer1 FROM dataset.table