如何在R中的列表中将矩阵动态列出为元素 [英] How to dynamically list matrices as elements in a list in R

查看:50
本文介绍了如何在R中的列表中将矩阵动态列出为元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此帖子类似于我的其他帖子

This post is similar to my other post

假设我有4个矩阵:

x1 <- matrix(1:9, nrow = 3)
x2 <- matrix(2:10, nrow = 3)
x3 <- matrix(3:11, nrow = 3)
x4 <- matrix(4:12, nrow = 3)

我想以如下方式将它们放入 list():

And I want to put them into a list() in a way like this:

[[1]]
[[1]][[1]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

[[1]][[2]]
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10


[[2]]
[[2]][[1]]
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    4    7   10
[3,]    5    8   11


[[3]]
[[3]][[1]]
     [,1] [,2] [,3]
[1,]    4    7   10
[2,]    5    8   11
[3,]    6    9   12

鉴于我有这个 list()来定义 x 中的哪个元素,以便在 list 中的每个元素中列出:

Given that I have this list() to define which element in x to list in each element in the list:

> list <- list(c(1,2),3,4)

[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

有没有一种以更动态的方式编写此列表的方法?目前,我正在使用此

Is there a way to write this list in a more dynamic way? Currently, I'm using this

x <- list(list(x1,x2),list(x3),list(x4))

我尝试使用以下代码,但它们不起作用:

I have tried using the below codes but they don't work:

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",list[[p]]))))
}

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",l))))
}

推荐答案

您太复杂了,不需要 for 循环和 lapply 循环,后者足以获得结果.
另外,由于 list 已经是基本的R函数,因此我将索引向量 list 的名称更改为 ilist .

You complicated too much, there is no need for a for loop and a lapply loop, the latter is enough to get the result.
Also, I have changed the name of the index vector list to ilist, since list already is a base R function.

ilist <- list(c(1,2),3,4)

mat <- ls(pattern = "x\\d+$", envir = .GlobalEnv)
x <- lapply(ilist, function(i) mget(mat[i], envir = .GlobalEnv))

输出是已命名成员的列表,名称是 mat 中的字符串"x *" .要获得未命名列表的列表,

The output is a list of named members, the names being the character strings "x*" in mat. To have a list of unnamed lists,

x <- lapply(ilist, function(i) unname(mget(mat[i], envir = .GlobalEnv)))

这篇关于如何在R中的列表中将矩阵动态列出为元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆