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

如何在R语言中按列表下标提取矩阵值并返回列表

Solution for Extracting Matrix Values by Nested Index List in R

Hey there! I see you're trying to pull values from a matrix using a nested list of indices while keeping the result in the same list structure—let's fix this up for you.

The Core Problem

When you tried using [] or [[]] directly with your index list A, R flattens all the nested indices into a single vector, giving you a flat result instead of the nested list you need. The solution is to iterate over each sub-list in A and extract the corresponding values from B one by one.

Step-by-Step Fix

We'll use lapply() here—it's ideal for this scenario because it applies a function to every element of a list and returns a new list with the exact same structure as the input.

First, let's reconstruct your example data to test with:

# Your nested index list
A <- list(c(1,2,3), c(4,5), c(6,7,8,9))
# Your matrix (defined as a 1-row matrix to match your example)
B <- matrix(c(3,4,12,35,35,13,2,3,34), nrow = 1)

Now run this code to get your desired list C:

# Iterate over each sub-index in A, extract matching values from B
C <- lapply(A, function(idx) B[idx])

Verify the Result

If you print C, you'll get exactly what you're looking for:

> C
[[1]]
[1]  3  4 12

[[2]]
[1] 35 35

[[3]]
[1] 13  2  3 34

Why This Works

  • lapply() loops through each sub-index vector in A one at a time.
  • For each sub-index vector idx, B[idx] pulls the corresponding values from the matrix.
  • The output is automatically wrapped into a list that mirrors the nested structure of A.

Quick Bonus for 2D Matrices

If your matrix B was multi-row/column (e.g., a 3x3 matrix) and your indices were pairs of (row, column), you could adjust the function like this:

# Example 2D matrix and index list
B_2d <- matrix(1:9, nrow = 3)
A_2d <- list(c(1,1), c(2,3), c(3,2))
# Extract values using 2D indices
C_2d <- lapply(A_2d, function(idx) B_2d[idx[1], idx[2]])

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:06:27