例如,我有一個包含 5 個向量的串列,并且想比較它們中的每一個。例子
L = list(c(1:5), c(-1:-5), c(3:7), c(-4:-8), c(5:9))
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] -1 -2 -3 -4 -5
[[3]]
[1] 3 4 5 6 7
[[4]]
[1] -4 -5 -6 -7 -8
[[5]]
[1] 5 6 7 8 9
我還有一個函式可以在串列的 5 個元素之間進行成對比較:
foo = function(x, y) t(x) %*% abs(y)
我想申請foo對我的串列進行成對比較。例如:成對比較(foo 的“x”和“y”):
[[1]]and [[2]]
[[1]]and [[3]]
[[1]]and [[4]]
[[1]]and [[5]]
[[2]]and [[3]]
[[2]]and [[4]]
[[2]]and [[5]]
[[3]]and [[4]]
[[3]]and [[5]]
[[4]]and [[5]]
...
My original file has 1000 elements
我嘗試使用:lapply(L, foo) 但我有以下訊息錯誤:```引數“y”丟失,沒有默認````
如何將 foo 應用于我的串列?
uj5u.com熱心網友回復:
也許是combn,apply和的組合lapply?
L = list(c(1:5), c(-1:-5), c(3:7), c(-4:-8), c(5:9))
foo = function(x, y) t(x) %*% abs(y)
setNames(lapply(apply(combn(seq_along(L), 2), 2, function(x) L[x]),
function(z) foo(z[[1]], z[[2]])),
apply(combn(seq_along(L), 2), 2, paste, collapse = "-"))
#> $`1-2`
#> [,1]
#> [1,] 55
#>
#> $`1-3`
#> [,1]
#> [1,] 85
#>
#> $`1-4`
#> [,1]
#> [1,] 100
#>
#> $`1-5`
#> [,1]
#> [1,] 115
#>
#> $`2-3`
#> [,1]
#> [1,] -85
#>
#> $`2-4`
#> [,1]
#> [1,] -100
#>
#> $`2-5`
#> [,1]
#> [1,] -115
#>
#> $`3-4`
#> [,1]
#> [1,] 160
#>
#> $`3-5`
#> [,1]
#> [1,] 185
#>
#> $`4-5`
#> [,1]
#> [1,] -220
由reprex 包( v2.0.0 )于 2021 年 10 月 25 日創建
uj5u.com熱心網友回復:
怎么樣outer?
> outer(L, L, Vectorize(foo))
[,1] [,2] [,3] [,4] [,5]
[1,] 55 55 85 100 115
[2,] -55 -55 -85 -100 -115
[3,] 85 85 135 160 185
[4,] -100 -100 -160 -190 -220
[5,] 115 115 185 220 255
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336732.html
