简体   繁体   English

从矩阵列表中删除矩阵

[英]remove matrix from a list of matrices

I have a list of 12 matrices called M and I'm trying to remove every matrix from the list that has 0 rows.我有一个名为M的 12 个矩阵的列表,我试图从列表中删除每个有 0 行的矩阵。

I know that I can manually remove those matrices with (for example, to remove the second matrix) M[2] <- NULL .我知道我可以手动删除这些矩阵(例如,删除第二个矩阵) M[2] <- NULL I would like to use logic to remove them with something like: M <- M[nrow(M)>0,] (but that obviously didn't work).我想使用逻辑来删除它们,例如: M <- M[nrow(M)>0,] (但这显然不起作用)。

Another option that could work is Filter in base R另一个可以工作的选项是base R中的Filter

Filter(nrow, M)

It works because 0 is considered as FALSE and all other values as TRUE它之所以有效,是因为 0 被视为 FALSE,所有其他值都被视为 TRUE

If there are also some attributes, gv from collapse could maintain it如果还有一些属性, gv from collapse可以保持它

library(collapse)
gv(M, function(x) nrow(x) > 0)

Use sapply() to get a logical vector of non-zero matrices, then use that vector to select/subset:使用sapply()获取非零矩阵的逻辑向量,然后使用该向量来选择/子集:

nzm <- sapply(M, function(m) nrow(m)>0)
M <- M[nzm]

Here is a one-liner.这是一个单线。

M <- M[sapply(M, nrow) != 0]

Data creation code数据创建代码

M <- lapply(1:5, function(n){
  if(n %% 2 == 0)
    matrix(nrow = 0, ncol = 2)
  else
    matrix(1:4, nrow = 2)
})

I think @Akrun has the cleanest answer.我认为@Akrun 有最清晰的答案。 I made this up before I saw his.这是我在看到他之前编造的。 It is reproducible and also explains a different way of going about it that I used with out thinking about more elegant solutions.它是可重现的,并且还解释了我使用的一种不同的处理方式,而没有考虑更优雅的解决方案。

# create list of matrices
matrixlist <- list(matrix(nrow=4,ncol=4,1),
     matrix(nrow=4,ncol=4,1),
     matrix(nrow=0,ncol=4,1),
     matrix(nrow=4,ncol=4,1))
matrixlist

# Identify matrices in my list that have at least one row
idx <- lapply(lapply(matrixlist, `[`), nrow) > 0

# subset the original list with this criteria
my_revised_matrixlist <- matrixlist[idx]

my_revised_matrixlist

All this was accomplished by Akrun's simple Filter(nrow, matrixlist)这一切都是由 Akrun 的简单Filter(nrow, matrixlist)完成的

Another option worth mentioning with purrr is keep() , discard() , or compact() . purrr值得一提的另一个选项是keep()discard()compact() The package purrr is my go-to these days with lists. package purrr是我最近的清单。

library(purrr)

# simplest by far
compact(M)

# probably a bit easier to remember what you did later
keep(M, ~ nrow(.) > 0)
discard(M, ~ nrow(.) == 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM