我有
A = list(a = matrix(1:4, 2), b = matrix(2:5, 2))
G = list(a = matrix(10:13, 2), b = matrix(25:28, 2))
columns <- list(a = matrix(3:4, 1), b = matrix(1:2, 1))
我想制作另一個串列中具有相同名稱的所有元素的交叉產品串列,所以我這樣做了purrr::map2(A, G, columns, `%*%`)。它看起來map2不允許超過兩個元素。有解決方法嗎?
Error in `stop_bad_length()`:
! Index 1 must have length 1, not 2
Backtrace:
1. purrr::map2(A, G, columns, `%*%`)
4. purrr:::stop_bad_element_length(...)
5. purrr:::stop_bad_length(...)
我也試過purrr::pmap(list(A, G, columns), %*%),但沒有運氣。
purrr::map2(A, G, `%*%`)效果很好。
uj5u.com熱心網友回復:
問題是您嘗試應用'%*%'的函式 ( ) 是一個只接受兩個引數而不是三個引數的函式。
對于您的問題,我建議Reduce(或purrr::reduce):在這種情況下Reduce,從兩個矩陣開始并將它們相乘。然后它將結果與第三個矩陣相乘。理論上你可以這樣繼續下去。
lapply(seq_along(A), \(k) Reduce('%*%', list(A[[k]],G[[k]], t(columns[[k]]))))
[[1]]
[,1]
[1,] 333
[2,] 496
[[2]]
[,1]
[1,] 486
[2,] 647
請注意,我必須在內部轉置矩陣,column因為它們的大小不合適。
uj5u.com熱心網友回復:
類似于@Cettt 的方法tidyverse,我們在其中接受list,pmap然后reduce與%*%. 請注意,需要轉置“列”t元素
library(purrr)
pmap(list(A, G, columns), ~ reduce(list(..1, ..2, t(..3)), `%*%`))
$a
[,1]
[1,] 333
[2,] 496
$b
[,1]
[1,] 486
[2,] 647
或帶有Mapfrom的選項base R
Map(\(x, y, z) Reduce(`%*%`, list(x, y, t(z))), A, G, columns)
$a
[,1]
[1,] 333
[2,] 496
$b
[,1]
[1,] 486
[2,] 647
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439269.html
上一篇:如何從有孩子的串列中洗掉專案
