You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用purrr或tidyverse优雅地实现向量列表到矩阵列表的转换

Hey there! Let's work through this problem together. First, let's start with the reprex you mentioned to align on the setup:

set.seed(123)
# 待填充的向量列表
all_list <- replicate(3, rnorm(4), simplify = FALSE)
# 空矩阵列表
empt_mat <- replicate(3, matrix(NA, nrow = 2, ncol = 2), simplify = FALSE)
# 我们要达到的目标结果
mat_list <- purrr::map(all_list, matrix, nrow = 2, ncol = 2)

To fill empt_mat with the vectors from all_list using tidyverse tools (and avoid clunky loops), purrr::map2 is the perfect fit here. It lets us iterate over two lists in parallel, pairing up corresponding elements from each list. Here's how to do it cleanly:

library(purrr)

# 填充空矩阵列表
filled_mat <- map2(empt_mat, all_list, ~ {
  # 将向量赋值到矩阵中,保留矩阵维度
  .x[] <- .y
  .x
})

# 验证结果是否和目标完全一致
identical(filled_mat, mat_list)
#> [1] TRUE

Let me break this down a bit:

  • map2(empt_mat, all_list, ...) iterates over both lists at the same time: .x refers to each empty matrix from empt_mat, and .y refers to the corresponding vector from all_list
  • Using .x[] <- .y instead of just .x <- .y is key here—it fills the existing matrix with the vector's values while preserving its 2x2 structure, rather than replacing the matrix with a plain vector
  • The modified matrix .x is returned each time, building up our final list of filled matrices

If you prefer even more concise syntax, you could rewrite the anonymous function using base R's replace function, though the above version is more explicit about what's happening:

filled_mat <- map2(empt_mat, all_list, ~ replace(.x, TRUE, .y))

Either way, you'll end up with exactly the same result as mat_list, no loops required!

内容的提问来源于stack exchange,提问作者user4687531

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:19:09